Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable using var after assignment to the variable [duplicate]

Tags:

javascript

Possible Duplicate:
is there any Advantage of redeclaring javascript variables?

Why does the following code display 1 rather than undefined:

a = 1;
var a;
alert(a);
like image 382
markm247 Avatar asked Aug 03 '26 06:08

markm247


1 Answers

1) var does not redeclare or delete a variable

2) even if it did, your code gets rewritten* using javascript hoisting rules (any variable or function declaration gets moved to the top of the nearest enclosing function) as follows:

var a;
a = 1;
alert(a);

(*effectively rewritten; see RobG's comments and links on entering of execution contexts for clarification)

like image 133
ninjagecko Avatar answered Aug 05 '26 19:08

ninjagecko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!