JavaScript Quiz #10 (Short Quiz)

Assume that we have the following short JavaScript code:

<script>
    var y = 10;

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

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

Will this code succeed or fail? and if it succeeds, what is the output of the alerts?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alerts will output undefined and 11 in sequence. Let’s understand why we will have these results.

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

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 that the if branch will not be 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 be 11.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>