Why does b in this code become a global variable when you call this function?
function myFunc() {
let a = b = 0;
}
myFunc();
The reason for this is that assignment operator or = has right-to-left associativity or evaluation. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this.
function myFunc() {
let a = (b = 0);
}
myFunc();
First, the expression b = 0
evaluated and in this example b
is not declared. So, The JS Engine makes a global variable b
outside this function after that the return value of the expression b = 0
would be 0 and it's assigned to the new local variable a
with a let
keyword.
We can solve this problem by declaring the variables first before assigning them with value.
function myFunc() {
let a,b;
a = b = 0;
}
myFunc();