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) {

on an HTML page:
<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="shadow.js"></script>
the result is:
So, the variable foo in the function is separate from the global variable foo.
Was this helpful?


Leave a Comment

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