As shown in the picture, js, why is undefined coming out of alert?

<html>
<body>
<script type="text/javascript">
    var amt=100;
    function a(){
        var amt =amt;
        alert(amt)
    }
    a()
</script>

</body>
</html>
Apr.27,2022

function a(){
 // var amt = amt; 
        
    var amt; 
    amt = amt;
    `undefined`
}

the so-called declaration advance can be understood as engine pre-scan code, putting all variables declared by var at the top of the scope

function a(){
    var amt = undefined;
    amt = amt;
    alert(amt)
}

the amt accessed at this time is naturally undefined.


-Magic dividing line-
positive solution:

 `amt`
 `var amt = amt` => `var amt; amt = amt`
 `amt`  `amt`  `amt`

the original answer is wrong:

amt 

-Magic dividing line-
Tip: please put the main body of the answer in the answer, not in the comment
Edit By: moon Lord LM

The

declaration has been promoted. It gives priority to the


scope of the internal variable, brother. The internal scope of the function cannot access the external amt variable


. Although the answer that has been adopted is correct, it does not explain the specific principle.
or the 2nd floor chenqiao is to the point. That is, the var declaration will execute
first in the domain, even if you get the variables of the outfield above the declaration, for example:
function a () {
console.log (amt) / / in the order of execution, Li should execute this
var amt = amt; / / but because there is a statement here, this is the first
console.log (amt);
}
so that the execution steps eventually become:
function a () {
var amt;
amt = amt;
console.log (amt);
console.log (amt);
}

Menu