Over a million developers have joined DZone.

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

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

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:

    var y = 10;

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


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.*


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.

#1 for location developers in quality, price and choice, switch to HERE.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}