What on earth is the promotion of variables?

Why does the second piece of code play 5?

    var x = 1;
    var y = 2;
    method(8)
    alert(x+y)
    function method(y) {
        x += 2;
        y += 3;
        alert(x+y)
    }
Mar.04,2021

if the internal variable of the function has a definition, find the variable inside the function, and if there is no definition, find the global variable. The variable inside the function has the same name as the global variable, and the former will overwrite the latter

.
var x = 1;
var y = 2;
method(8)
alert(x+y)
function method(y) {
    x += 2; //x=1+2
    y += 3; //y=8+3
    alert(x+y)
}
The y in the

function is the y in the parameter, but the x in the function is still the global x


what you need to understand in this question is not the promotion of variables, but the scope of variables. Your code is the same as the following code, despite the fact that the parameter is y , which are actually two different values

.
    var x = 1;
    var y = 2;
    method(8)
    alert(x+y)
    function method(a) {
        x += 2;
        a += 3;
        alert(x+a)
    }
Menu