Based on A re-introduction to Javascript
//declaring with var keyword attaches it to current scope
var x = 2;
//declaring without var keyword attaches it to global scope
y = 5;
//general rule is to keep the global scope clean.
//associate as many of your variables to objects as possible.
var x = 2;
var y = 2.3;
var z = parseInt('5');
// > 5
var numberStr = 5 + '7';
// > '57'
+ numberStr;
// > 57
x = parseInt('huh?');
// > NaN
var word = 'hello';
// > 'hello'
word.length;
// > 5
word[1];
// same as word.charAt(1);
// > 'e'
word.toUpperCase();
// > 'HELLO'
word
// > 'hello'
var isBool = true;
if(isBool) { // some code }
// defined variables are truth-y
// undefined or null variables are false-y
var msg = 'Hi There!';
if(msg) { console.log('msg');} else { console.log('not truthy');}
// > 'Hi There!'
var myObj = new Object();
var yourObj = {};
// these are semantically equivalent. second is more convenient.
var thatObj = { aProp : 'something', anotherProp : 'someone' };
thatObj.aProp;
// > 'something'
thatObj['aProp'];
// > 'something'
var finalObj = { hello : function(name) { console.log('hello ' + name); } };
finalObj.hello('ryan');
// > hello ryan
finalObj['hello']('world');
// > hello world
var firstArr = new Array();
var secondArr = [];
// do the same thing. similar to Object instantiation
var thirdArr = ['dog', 'cat', 'bunny'];
thirdArr[1];
// > 'cat'
thirdArr[1] = 'unicorn';
thirdArr[1];
// > 'unicorn'
thidArr.length;
// > 3
thirdArr[9] = 'cat';
thirdArr;
// depends on browser:
// ['dog', 'unicorn', 'bunny', undefined x6, 'cat']
function add(x, y)
{ var total = x + y;
return total;}
add(2, 3);
// > 5
add();
// > NaN
add(5, 6, 7);
// > 11 (7 is ignored)
if(add)
{ console.log('add function exists');}
// > 'add function exists'
<script>
console.log('hello world');
</script>
HelloWorld.js >
console.log('hello world');
index.html >
<html>
<head>
<script src="HelloWorld.js"></script>