JavaScript - Variables
// JavaScript - Variables
New variables in JavaScript are declared using the var keyword:
var xyz;
var xyz = "hello";
If we declare a variable without assigning it any value, its value is undefined.
If we do not use the var keyword when declaring a variable, or assigning a value
to a variable, JavaScript creates that variable in the global space which may lead
to namespace collision.
The var keyword is only applied to one variable.
(function(){
var a = b = 3;
})();
In the above code, only a is local to that function, and b is a global variable,
and therefore:
console.log("a defined? " + (typeof a !== 'undefined')); //logs "a defined? false"
console.log("b defined? " + (typeof b !== 'undefined')); //logs "b defined? true"
If we forget to declare a variable with a var keyword, JavaScript assume that
we use a global property of the window object
page revision: 2, last edited: 14 Nov 2016 20:01