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

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

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 }}