Local var not overriding parameter with same name?

It just blew my mind:

function f(x) {
    var x;
    console.log(x); // prints 100!
}

f(100);
Run codeHide result

I always thought that whenever you declare a local variable, everything that was declared earlier is hidden behind it. Why var xdoesn’t it x undefined, as it was in other situations?

Compare with this code, which behaves the way I used:

var x = 100;
function f() {
    var x;
    console.log(x); // prints undefined as expected
}

f();
Run codeHide result
+4
source share
3 answers

For function code, parameters are also added as bindings to this environment record.

A specific parameter is xmatched to the current function. Since it is xalready declared in the function as a parameter var x,; the ad will be ignored.

More details: http://es5.imtqy.com/#x10.5

+1

var, x . , undefined 100, .

+2

MDN # var:

... JavaScript, .

, x f ( ), ( var) x redeclaration ( , f, ).

In the second example, it is xdeclared inside a function f. Therefore, when viewing the values xfor the transition to, logwe use this xinside f(and not external), and since we obviously did not give it a value (initializing it), its value will be undefined.

0
source

Source: https://habr.com/ru/post/1689929/


All Articles