JavaScript Quiz #7

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>

What is the output of each alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The result will be as follows boolean then string then string. Let’s understand why we have these results. In the first expression (which is a very straightforward):

var result = typeof(str instanceof String);

Will executed as follows:
1. str instanceof String will return true.
2. typeof (true) will return "boolean".

In the second expression:

var result = typeof typeof(str instanceof String);

Why does result will be string, this is because the expression will be executed as follows:
1. str instanceof String will return true.
2. typeof (true) will return "boolean" as you notice here typeof(true) returns a String that contains “boolean” value. It is important to know that JavaScript typeof operator always returns String.
3. Finally, it is now clear that typeof ("boolean") will return "string".

In the third expression:

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

It is much similar to the second expression, result will return “string” because the third expression will be executed as follows:
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 is the result of ;):

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

One thought on “JavaScript Quiz #7

  1. Pingback: JavaScript Quiz #7 | Technical Advices, "An advice can always help"

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>