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));