Over a million developers have joined DZone.

JavaScript Quiz #10

This week's JavaScript quiz will test your knowledge of block scopes. We're moving out of the basics and into more advanced topics.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

If you haven't checked out JavaScript quizzes 7, 8, and 9 take some time to look at those after doing this one.  Each one builds on the other and they get progressively more difficult. Assume that we have the following JavaScript code:

<script>
    var y = 10;

    if (!(x in window)) {
        var x = 10;
    } else {
        ++y;
    }

    alert(x);
    alert(y);
</script>

Question: Will this code succeed or fail? And if it succeeds, what is the output of the alert?

*Write your answer on a piece of paper and then read the answer.*


Answer:

The code will work fine. The alerts will output undefined and 11 in sequence. Let’s understand why we get these results.

First of all, the variable y is created and is assigned to 10, then we come to the following if statement:

if (!(x in window)) {
    var x = 10;
}

Excluding functions blocks, JavaScript does not support block scopes (such as if or for loop blocks). This means that x, which is defined inside the if statement, will be available in window scope even if the if branch is not executed at all.
This means that x in window will be evaluated to true which will result in the if branch not being executed at all. The else branch of the if statement will be executed, which will add 1 to the current value of y so it will add up to 11.

This explains why the final result will be undefined and 11.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}