JavaScript Quiz #7
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.
Join the DZone community and get the full member experience.
Join For FreeAccess over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required
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));
#1 for location developers in quality, price and choice, switch to HERE.
Published at DZone with permission of Hazem Saleh , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}