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?
When you declare a variable, you should also initialize it. Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.
To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
Declaration: Variable is registered using a given name within the corresponding scope (e.g., inside a function). Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.
Declaring final variable without initializationIf you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values.
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!).
@jmar777's answer is definitely the best explanation and breakdown of the spec. However, I find that for us hands-on learners, a bit of illustrative code is helpful! ;)
The Basic Idea
window.varName = value
).undefined
(even if they immediately get assigned a different value in the first line of code).Thus, initialization isn't a term that matters to us. We declare and assign, and the Javascript engine initializes.
So to directly answer the example in your question:
var example;
declares a variable, which gets assigned a value of undefined
during initialization.var example = "hi"
declares a variable, which also gets assigned a value of undefined
initially, but when that line of code is actually reached during execution, it gets re-assigned to the string "hi".
Illustrative Code
function testVariableDeclaration() {
// This behaves 'as expected'....
console.log(test2, 'no value assigned yet'); // --> undefined 'no value assigned yet'
// ....but shouldn't our actual expectation instead be that it'll throw an error since
// it doesn't exist yet? See the final console.log() below!
// As we all know....
test1 = 'global var'; // ....a variable assignment WITHOUT declaration in the current
// scope creates a global. (It's IMPLICITLY declared.)
// But a little counter-intuitively....
test2 = 'not global'; // Although this variable also appears to be assigned without
// declaration like 'test1', the declaration for 'test2' that
// appears *later* in the code gets hoisted so that it's already
// been declared in-scope prior to this assignment.
console.log( test1, window.test1 === test1 ); // --> 'global var' TRUE
console.log( test2, window.test2 === test2 ); // --> 'not global' FALSE
var test2; // As shown by the above console.log() outputs, this variable is scoped.
console.log( test3 ); // Throws a ReferenceError since 'test3' is not declared
// anywhere, as opposed to the first console.log() for 'test2'.
}
Effects of 'Scope' on Declaring/Assigning
What makes the difference between declaration and assignment even clearer is that declaring a variable always creates a new variable within the current scope (myVar
scopeB), even if a variable of the same name already existed in a parent scope (myVar
scopeA). Then we can assign a new value to myVar
scopeB at any point in the current scope without re-declaring it. (This assignment does not affect the value of myVar
scopeA.) Once the end of scopeB is reached, myVar
scopeB will no longer be available for assignment.
On the flip side, if we assign a value to a variable within a given scope without declaring it in that scope, it'll be assigned to the next-highest-up declaration in the 'scope chain' (or a global will be implicitly declared if no higher declaration is found).
Thus, a variable need only be declared once per scope, with each declaration overriding any declarations made in parent scopes (i.e. it creates a distinct variable). But it must be declared in-scope if it's meant to be unique to that scope. Assignment can happen as many times as desired, but only affects the most 'closely-declared' variable (for lack of a better term).
The only difference is that the var
statement will initialize any declared variables without a value to undefined
.
In both examples, you are declaring a variable.
If you assign a value to a variable without the var
statement, it will go down the scope chain looking for declared variables, eventually falling back to the global window
object.
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