A JS interview question, continuous assignment, solution

// 
(function(){
 var  x = c =  b = {a:1}
})()

console.log(x.a); // error , x is not defined
console.log(c,b) // {a: 1} {a: 1}

Why is x.a undefined here

Apr.05,2021

this involves the knowledge of variable scope enhancement:
var x = c = b = {ahol1} is equivalent to

.
b = {a:1};  //var
c = b;  //var
var x = c;

if you use the var keyword, this variable will only take effect within the function that defines it. Without the var keyword, this variable is promoted to a global variable.
therefore, an error is reported directly when using x.a directly outside, because in the external scope, x is not defined at all, let alone x.a. C and b are global variables that can be accessed.

Menu