Javascript: typeof operator
May 22, 2017
It’s no secret that when it comes to type safety, you’re on your own in JavaScript. However, the language does provide some useful tools to help infer the type of the object you’re dealing with.
In this blog post, we will look at one such method i.e typeof
.
typeof
The typeof
operator return a string containing the information about the type of object.
Eg:
typeof 10 //returns 'number'
typeof 'so cool!' //returns 'string'
typeof function(){} //returns 'function'
typeof {} //returns 'object'
Alright, looks like we have what we need for all of our type checking needs, right? Well. No!
typeof
can return one of the following seven possible values:
- number
- string
- boolean
- object
- function
- undefined
- symbol
Looking at that list, we can start to see the problem. There is no way to detect custom types using the typeof
operator. This is where the instanceof
operator comes in handy. Read more about the instanceof operator
One of the most common uses of the typeof
operator is to check if a variable or property is defined.
const woof;
typeof woof === 'undefined'; //returns true
woof ==== undefined; //returns true;
typeof doYouEvenExistBro === 'undefined'; //returns true;
const obj = {};
typeof obj.dogsAreTheBest === 'undefined'; //returns true;
As you can see above, the typeof
operator can be used to test for the data type of undefined
on both declared & undeclared variables.
Caveat
If you want to check if a given value is specified (it’s neither undefined or null), you’ll find yourself pulling your hair out if you relied on the typeof
operator alone.
The reason being that typeof
operator returns 'object'
when used to check the data type of null
.
This is considered a bug in the language. Alas, JavaScript is so widely used that patching this bug would cause existing programs to break.