Your browser does not support JavaScript!
Upvotes Anonymous 10 User 0

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:
So, the variable foo in the function is separate from the global variable foo.
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License