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

JavaScript Quiz #7

DZone's Guide to

JavaScript Quiz #7

In this installment of the JavaScript quiz, we'll be working with with typeof operatior. The typeof operator always returns a string.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Today we're woring with the typeof operatior in JavaScript. Let's get down to busness! Assume that we have the following short JavaScript code:

<script>
    var str = new String("Hello");

    var result = typeof(str instanceof String);
    alert(result); //What is the output of the alert? 

    result = typeof typeof(str instanceof String);
    alert(result); //What is the output of the alert? 

    result = typeof typeof typeof(str instanceof String);
    alert(result); //What is the output of the alert? 
</script>

Question: What is the output of the alert and why?

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

Answer:

The result will be a boolean then string then string. Let’s understand why we get these results. In the first expression (which is a very straightforward) we have:

var result = typeof(str instanceof String);

Which is executed in the following two steps:
1. str instanceof String will return true.
2. typeof (true) will return "boolean".

In the second expression:

var result = typeof typeof(str instanceof String);

This will result in a string, and here's why:
1. str instanceof String will return true.
2. typeof (true) will return "boolean" . As you'll notice, typeof(true) returns a String that contains “boolean” as the value. It is important to know that the JavaScript typeof operator always returns a String.
3. Finally, it's clear that typeof ("boolean") will return "string".

Here's the third expression:

var result = typeof typeof typeof(str instanceof String);

It is similar to the second expression: result will return “string” because the third expression will be executed in the following steps:
1. str instanceof String will return true.
2. typeof (true) will return "boolean".
3. typeof ("boolean") will return "string".
3. Finally, typeof ("string") will return "string".

So now you can guess what what the result is:

alert(typeof typeof typeof typeof typeof typeof typeof(str instanceof String));



Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}