I'm curious to know the difference between declaring a variable, and initializing a variable. e.g.
var example; // this is declaring
var example = "hi" // initializing? Or just "adding a value"?
I don't think I'm right there, but what exactly is the definition of each? Or do they basically mean the same thing?
Edit: @ThisClark said something in the comments, and I went to prove him wrong, and upon reading the spec some more I learned something:
Here's an informative except from the specification:
A
var
statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized toundefined
when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
Based on my reading of this, the following points describe the behavior (and "correct-ish" usage of the terms) you asked about in your question:
A variable declaration (e.g., var foo
) causes that variable to be created as soon as the "lexical environment" is instantiated. For example, if that variable were defined within a function body, that function is the "lexical environment", and so variable creation coincides with the instantiation of the function itself.
Obviously, variable declarations may or may not be created with an initializer (i.e., the right-hand expression that resolves to the variable's initial value). That's a pretty non-specification usage of the term "initial value", though... let's dig into that a bit more:
Technically, per the specification notes here, all variables are initialzed with the value undefined
:
variables are created [...] and are initialized to undefined
Emphasis on "technically" there, as this is largely academic if an initializer was also provided.
Based on what we've already covered, it should be understood that the statement var foo;
could exist anywhere within a function body, and moving it anywhere else within the same function would have no effect on the runtime semantics of the function itself (regardless of if/where any actual assignments or other references to foo
take place). If that's still confusing, re-read the previous points.
The last bit of behavior is the most intuitive part, and that's the assignment of the initializer. This assignment takes place when that line of code is actually executed (which, again, isn't the same point in time when the variable technically got created).
So, to quickly recap:
var
) are always initialized with undefined
upon the initialization of their lexical environment.Hope that helps (and that I didn't terribly misinterpret the spec!).