简体   繁体   中英

JavaScript operation order

When instantiating two variables in the same instruction:

var foo = 1,
    bar = foo + 1;

in V8, this yields foo == 1 and bar == 2 ,

var bar = foo + 1,
    foo = 1;

and this yields foo == 1 and bar == NaN .

Is the order of executed operations guaranteed? Or is it safer to declare foo and bar separately?

var foo = 1;
var bar = foo + 1;

or even

var foo, bar;
foo = 1;
bar = foo + 1;

As you have noted correctly, the variable declaration expressions will be evaluated from left to right. The left hand side of the assignment will be evaluated first, right hand side of the assignment expression will be evaluated next, and then assigned.

In the second case, you got NaN , because of variable hoisting . When JavaScript sees

bar = foo + 1,

it will know that foo is defined in the current context, but not yet assigned a value. So, by default, it uses undefined for foo .

console.log(undefined + 1);
# NaN

That is why NaN is assigned to bar .

According to the ECMA 5.1 Standard Docs' Variable Statement section , variable declaration will be evaluated like this

VariableStatement:
    var VariableDeclarationList ;

VariableDeclarationList :
    VariableDeclaration
    VariableDeclarationList , VariableDeclaration*

Here, the production will be evaluated like this

The production VariableDeclarationList : VariableDeclarationList , VariableDeclaration is evaluated as follows:

  1. Evaluate VariableDeclarationList .
  2. Evaluate VariableDeclaration .

So, the left most assignment expressions should be evaluated first, and at the last only, the right most one. So, the behavior you see, is the expected behavior.

When declaring and initializing variables in the same instruction, javascript executes the actions in exactly the order you would expect.

For example,

var foo = 1,
    bar = foo + 1;

is perfectly valid, and will never produce errors. On the other hand

var bar = foo + 1,
    foo = 1;

will produce bar === NaN , just like you stated, because the first thing that will happen is bar will be initialized as foo + 1 , where foo is technically undefined .

tl;dr Yes.

The difference between

// Case 1 var foo = 1, bar = foo + 1;

and

Case 2 var bar = foo + 1, foo = 1;

is that in the first case foo is already defined as 1 so your operation is 1+1 In the second case the moment you define bar, foo is still undefined. Although it is already declared.

In JS all declaration will happen before the program runs. So even if all your var statements are at the bottom of you code it would work. See here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM