Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Quiz #10

DZone's Guide to

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
Free Resource

Tips, tricks and tools for creating your own data-driven app, 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.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:
javascript

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}