Possible Duplicate:
Difference between using var and not using var in JavaScript
I understand that I should always use 'var' to define a local variable in a function.
When I define a global function, what's the difference between using 'var' ?
Some of code examples I see over the internet use
var globalVar = something;
globalVar = something;
What's the difference?
Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.
myVariable = 'abc'; It's possible that you declare a variable in JavaScript without using any keyword var , let , const . It simply means that you have created a global variable. The result shows test , which means it works!
This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.
Scoping — the main reason to avoid var var variables are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } .
Well, the difference is that technically, a simple assignment as globalVar = 'something';
doesn't declare a variable, that assignment will just create a property on the global object, and the fact that the global object is the last object in the scope chain, makes it resolvable.
Another difference is the way the binding is made, the variables are bound as "non-deletable" properties of its environment record, for example:
var global1 = 'foo';
delete this.global1; // false
global2 = 'bar';
delete this.global2; // true
I would strongly encourage you to always use the var
statement, your code for example will break under ECMAScript 5 Strict Mode, assignments to undeclared identifiers are disallowed to avoid implicit globals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With