Variable Shadowing in JavaScript

If there's a variable in the global scope, and you'd like to create a variable with the same name in a function, that's not a problem in JavaScript.

The variable in the inner scope will temporarily shadow the variable in the outer scope.

So if we include this JavaScript:

var foo = 5;

function AlertFoo(foo) {
    alert(foo);
}

AlertFoo(2);

on an HTML page:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="shadow.js"></script>
</head>
<body>
</body>
</html>

the result is:

result in alert dialog

So, the variable foo in the function is separate from the global variable foo.

Comments

April 19, 2020 05:04

test comment

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.