Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript global variable with 'var' and without 'var' [duplicate]

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?

like image 920
Moon Avatar asked Aug 01 '11 16:08

Moon


People also ask

Can I declare variable without var in JavaScript?

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.

What happens if we declare a variable * without * the VAR let keyword?

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!

Why we should not use VAR in JavaScript?

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.

Why is var no longer used in JavaScript?

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 { } .


1 Answers

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.

like image 56
Christian C. Salvadó Avatar answered Nov 01 '22 15:11

Christian C. Salvadó