3

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);
Community
  • 1
  • 1
markm247
  • 97
  • 9
  • Why do you _think_ it should alert `undefined`? You've clearly assigned `a`! – Matt Ball Oct 05 '12 at 02:39
  • My initial assumption was that the variable would be redeclared. I knew from running the code the assignment remained but didn't know why. I guess I could have left off the 'rather than undefined' part but thought it would add some context. – markm247 Oct 05 '12 at 02:58

1 Answers1

9

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)

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
  • +1 for variable hoisting – jimp Oct 05 '12 at 02:47
  • Interesting, that's a generic rule of the javascript interpretors ? – Antoine Oct 05 '12 at 02:47
  • 1
    @AntoineLafarge—that is the specified behaviour on [entering an execution context](http://ecma-international.org/ecma-262/5.1/#sec-10.4) (global or function) per ECMA-262. [Declared functions and variables](http://ecma-international.org/ecma-262/5.1/#sec-10.5) are added to the variableEnvironment first, then the code is executed. Your answer was more correct than this one. – RobG Oct 05 '12 at 02:50
  • @RobG "hoisting" is still the right concept, even if "moved" is the wrong verb to _explain_ hoisting. – Matt Ball Oct 05 '12 at 03:01
  • @MattBall—I think that when answering a technical question, appropriate technical terms (preferably from related standards and specifications) should be used. Jargon may be helpful, but only where it adds to clarity and it should be explained, it should not be the entire answer. Saying "your code gets rewritten" is misleading. While it might be said that a compiler re-writes code to some other machine–specific code, I think equating that to re–writing the original is drawing a long bow. – RobG Oct 05 '12 at 03:15
  • @RobG I'm not disagreeing with you. If the answer is partially incorrect and the answerer declines to edit according to your comment, correct the answer or post your own. – Matt Ball Oct 05 '12 at 03:17