The way javascript compiler read line of code

i am looking for the order how the compiler reads the code. is it reading the code from left to right or from right to left. like

var a=b=c=100;

in above code which variable will be declared first how the value will be assigned.?



Let's consider the example you provided:

var a = b = c = 100;

This is equivalent to:

var a;   // declare a

c = 100; // assign 100 to c
b = c;   // assign 100 to b via c
a = b;   // assign 100 to a via b

The thing is that in JavaScript if you assign a value to variable that you haven't declared then that variable becomes a global variable. That's the reason the above code works. However, it could also cause problems like in this example:

console.log("a", typeof a); // undefined
console.log("b", typeof b); // undefined
console.log("c", typeof c); // undefined

function foo(x) {
    var a = b = c = x;


console.log("a", typeof a); // undefined
console.log("b", b); // 100
console.log("c", c); // 100

What you really want to do is:

var a = 100, b = a, c = b;

This is equivalent to:

var a, b, c; // all variables are hoisted

a = 100;
b = a;
c = b;

In JavaScript variable declarations are all hoisted to the top of the current scope (function scope for var and block scope for const and let). However, assignments happen in order from left to right. Variables which are declared but not assigned a value yet have the value undefined.


The following assignemt:

var a=b=c=100;

is equivalent to the following assignment:

var a = (b = ( c= 100 ));

That being said it seems that the mulitple assigment is right associative.


From MDN docs:

Assignment operators are right-associative, so you can write:

a = b = 5; with the expected result that a and b get the value 5. This is because the assignment operator returns the value that it assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

So for var a=b=c=100; first c, then b and then a will be assigned to 100.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.