typeof returns the data type of a variable. typeof may return any of these value for a particular variable.
Now, let us see some examples:
var x = 45; typeof x; //returns "number" var n = 0.06; typeof n; //returns "number" var s = "rishiraj.xyz" typeof s; //returns "string" var s1 = "" typeof s1; //returns "string" var yes = true; typeof yes; //returns "boolean" var f = "true"; typeof f; //returns "boolean"
>>>Infinity-Infinity >>>NaN >>>Infinity/2 >>>Infinity >>>Infinity-90 >>>Infinity
Now, let’s see, the typeof value of Infinity and NaN
typeof Infinity; //returns "number"
var i = infinity typeof i; //returns "number"
NaN or ‘Not a Number’ is actually a number according to the typeof operator. (strange ?) This is one of those things that make JS a different kind of language
typeof NaN; //returns "number"
We get NaN as a result when we do some irrelevant operation like multiplying a number say, 5 with a letter, say r.
var i = 5*r //i is NaN
var i = '5' //here i is a string i = i+1;
The above code is not an error, when we incremented i, the i was internally type-casted to number. This can be verified using the typeof operator.
typeof i; //returns "number"
>>>foo foo is not defined typeof foo; // returns "undefined"
The same is true for uninitialized value as well.
var something typeof something; // returns "undefined"
var something = null; typeof something; //returns "object"
null is of type object, as we just saw in the code above.
Let us see some more examples for clarification:
//here value of i will be NaN; var i = 1 + undefined; var j = 1*undefined; //use console.log() to print the value of i console.log(i); //returns "NaN" console.log(j); //returns "NaN"
//here value of i will be 1; var i = 1 + null; var j = 1*null; //use console.log() to print the value of i console.log(i); //returns 1 console.log(j); //returns 0