Declaration vs Initialization of Variable?

I am curious to know the difference between variable declaration and variable initialization. eg.

var example; // this is declaring var example = "hi" // initializing? Or just "adding a value"? 

I don't think I'm here, but what is the definition of everyone? Or do they basically mean the same thing?

+6
source share
7 answers

Edit: @ThisClark said something in the comments, and I went to prove that he was wrong, and after reading the spec, I found out something:

Here is informative, except for the specification :

Operator

A var declares variables that are bound to the current execution contexts of the VariableEnvironment. Var variables are created when their containing Lexical environment is created and initialized to undefined when created. [...] The variable defined by the VariableDeclaration variable with the initializer is assigned the value of its initializer AssignmentExpression when the VariableDeclaration is executed, and not when the variable is created.

Based on my reading of this, the following paragraphs describe the behavior (and "right-ish" use of terms) that you asked about in your question:

  • Declaring a variable (for example, var foo ) forces this variable to be created as soon as the "lexical environment" is created. For example, if this variable was defined inside the body of the function, this function is a “lexical environment”, and therefore the creation of the variable coincides with the creation of the function itself.

  • Obviously, variable declarations may or may not be created using an initializer (i.e., a right expression that resolves the initial value of a variable). This is a rather nonspecific use of the term “initial meaning,” though ... let it be a little more:

  • Technically, in the notes to the specification here, all variables are initialized to undefined :

    variables are created [...] and initialized undefined

    The emphasis on "technically" is there, as it is largely academic if an initializer was provided.

  • Based on what we have already examined, it should be understood that the var foo; can exist anywhere in the body of the function, and moving it to another place inside the same function will not affect the semantics of the runtime of the function itself (regardless of whether there are actual assignments or other references to foo ). If this is still confusing, re-read the previous paragraphs.

  • The last bit of behavior is the most intuitive part and purpose of the initializer. This assignment is executed when this line of code is actually executed (which again does not coincide with the time when the technically obtained variable).

So, to quickly return:

  • All variable declarations (which use var ) are always initialized with undefined when initializing their lexical environment.
  • This initialization is probably not considered a destination, in a technical sense (ha, @ThisClark, you were wrong !!). :)
  • Appointments are an easy part as they behave as you expect (and at a point in time).

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

+10
source
Answer to

@ jmar777 is by far the best explanation and breakdown of the spec. Nevertheless, I find that for us practical students a little illustrative code is useful !;)


main idea

  • "Declaration" makes the variable available to the entire area.
  • 'Assignment' gives the variable a specific value at this point in the code. If you try to assign a value to a variable that has never been declared in this region or the parent region, the variable is implicitly declared in the global region (equal to the type window.varName = value ).
  • “Initialization” is what happens “backstage” or “under the hood,” so to speak. At run time, all declared variables are initialized with the initial assignment undefined (even if they immediately get the assigned other value in the first line of code).

Thus, initialization is not a term that matters to us. We declare and assign, and the Javascript engine is initialized.

So, to directly answer the example in your question:

  • var example; declares a variable that is set to undefined upon initialization.
  • var example = "hi" declares a variable that first gets an undefined value, but when this line of code is actually reached at runtime, it gets an overridden hello string.


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 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 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'. } 


Scale effects on declaration / assignment

The difference between a declaration and an assignment is different, then a variable declaration always creates a new variable in the current scope ( myVar scopeB ), even if a variable with the same name already exists in the parent scope ( myVar scopeA ). Then we can assign a new value to myVar scopeB at any point in the current scope without re-declaring. (This assignment does not affect the value of myVar scopeA .) Upon reaching the end of scopeB , myVar scopeB will no longer be available for assignment.

On the other hand, if we assign a value to a variable in a given area without declaring it in that area, it will be assigned to the next-high-up declaration in the "scope chain" (or global will be declared implicitly if a higher declaration is not found).

Thus, a variable should only be declared once for each area, with each declaration overriding any declarations made in the parent areas (i.e., creating a separate variable). But it must be declared in the area, if it must be unique to this area. Assignment can occur as many times as required, but affects only the most “strongly declared” variable (due to the lack of a better term).

+2
source

The declaration basically means the introduction of a new facility into the program. Initialization gives a variable its first value. So basically your above example is correct.

0
source

An announcement is an introduction to the program of a new name.

 var test; // Is this a declaration ? 

Initialization refers to the "assignment" of a value.

 var test = {first:"number_one"} // Now that object is initialized with value 
0
source

The only difference is that the var statement will initialize any declared variables without an undefined value.

In both examples, you are declaring a variable.

If you assign a value to a variable without the var operator, it will go down the chain of domains that looks for declared variables, eventually retreating to the global window object.

0
source

There is a small thing that you are missing here. The analogy for understanding the concept is as follows. A specific value must be assigned for each variable.

The default value for all variables (unless explicitly specified undefined)

 1) let example; // this is declaring and initializing with undefined 2) example="hi"; // this is assigning the value to hi 3) let example = "hi" // this is declaring and initializing with "hi" 

therefore, the third operator actually coincides with 1 + 2.

Now the question may arise that when statement 3 is possible, why do we need statement 1?

The reason is to expand the scope of the variable.

eg. let's say that the variable is required in line number 8. But the value is not available until late and this is also in the code block.

 1) { 2) let a; 3) try{ 4) a=someFunctionWhichMayThroeException(); 5) } 6) catch(e){ 7) a=100; 8) } 9) someFunctionOnA(a);// the variable is required here 10) 11) } 

By declaring the above variable, we have increased the scope of the variable, so it can be used outside the try block.

PS: this is just a trivial use case.

0
source

Taken directly from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined :

The global undefined property is the primitive value undefined. This is one of the primitive types of JavaScript.

Just declaring a variable in Javascript, like var example , initializes it with a primitive value of undefined. This means that the following two expressions are equivalent:

 //equivalent expressions var ex1; var ex2 = undefined; //true! alert(ex2 === ex1); 

What I do not know and cannot check at this time is how far back in the history of the web browser the warning will be displayed correctly. For example, does this warning work in IE6 or on some obscure Blackberry phone? I can’t say for sure that this is universal, but at least it works in the latest versions of Firefox, Chrome and Safari at the time of writing.

-1
source

All Articles