1

Why does the alert print 2 in the below example? var a is unknown to function n...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>Test Doc</title>
    <script type="text/javascript">
        var a = 1;
        function f() {
            var a = 2;
            function n() {
                alert(a);
            }
            n();
        }
        f();
    </script>
</head>

<body>


</body>
</html>
1
  • "var a is unknown to function n..." that would be the case in PHP. Luckily JavaScript is not PHP. Commented Sep 12, 2011 at 5:22

3 Answers 3

5

JavaScript functions inherit their parent's scope. Inner variables shadow parent scope variables with the same name.

Further Reading.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Spot on and good link. @user443946, search for "Nested functions and closures" within that document.
0

It would alert "2".

Test your javascript examples here : jsfiddle.net

Your example is pasted here : your javascript example

And why the heck is var a unknown to n() ??

Comments

0

a is decalred as a global variable and given a value of 1. a is also declared inside the function f() and given a value of 2. Function n() is declared inside the function f() and called after the assignment to the "inner" a.

So when n is called, the identifier a will be resolved from the scope of n. The first variable object on the scope chain with an a property is the one declared in f, so its value is returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.