Javascript Typeof Example
When writing code in whatever programming language, you will inevitably have to deal with different types of variables and treat them accordingly. What happens when you are not the one who defines your variables type? Let’s have a look!
Typeof syntax
typeOf
can be used in two ways: as a function and as an operator. Though the syntax changes a bit, it is mainly the same. Here’s how you use it in function form:
typeof(myVar);
And this is how you use it in the operator form:
typeof myVar;
Obviously, typeof
will take a value and return it’s type.
As we all know, there are several primitive types in Javascript:
- string
- boolean
- number
- object
- null, undefined
such as “Twinkle twinkle” and “little star”
true and false values
all numbers and pseudo-numbers such as 3.14, infinity and NaN (which ironically means Not-A-Number!)
which includes functions and arrays
which contains every special value of variables that does not fall into the above categories
Let’s see this operator in action in the code snippet below:
typeof 7.5 // "number" typeof NaN // "number" typeof false // "boolean" typeof "wcg" // "string" typeof undefined // "undefined" typeof {} // "object" typeof null // "object" typeof function(){} // "function"
You will have noticed that while the typeof
operator correctly guesses that 7.5
is a number, it considers NaN
as a number too. It works correctly for boolean and string values, and also attributes the “undefined” type to undefined
, but then considers null
and object too when it’s officially not an object. Also, functions are getting special treatment by Javascript, when they are objects.
However it may seem a bit problematic, if you just remember these small issues, you will not only be able to overcome them, but also use them to your advantage.
Download the source code
This was an example of typeof in Javascript.
Download the source code for this tutorial:
You can download the full source code of this example here: TypeOf