javascriptvariable-declarationvariable-initialization

Declaring vs Initializing a variable?


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?


Solution

  • 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 to undefined 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:

    So, to quickly recap:

    Hope that helps (and that I didn't terribly misinterpret the spec!).