How can we check if something is undefined
?
We can compare it against the variable itself:
var something
something === undefined // true
Fun fact, before ES5, undefined
was overwritable so you would use typeof
:
var something
typeof something === 'undefined' // true
How about null
?
We can do something similar:
var something = null
something === null // true
However, typeof
won’t work here:
typeof null // 'object'
String checks are consistent with typeof
:
var something = ''
typeof something // 'string'
And we could use it to check if it’s a number as well:
var something = 42
typeof something // 'number'
But there’s a catch:
var something = parseInt('foo') // NaN
typeof something // 'number'
So to check if something’s truly a number:
typeof something && !isNaN(something)
Because type casting happens even during comparison:
1 > '0' // true
1 > '1' // false
Function can be checked with typeof
:
var something = function() {}
typeof something // 'function'
So what about an array?
Well there’s always the length
property:
var something = []
something.length >= 0 // true
But it will break for undefined
and null
:
var something
something.length // TypeError
something = null
something.length // TypeError
So can we use typeof
to check if a variable is an array?
var something = []
typeof something // object
It seems like it’s not consistent as well.
The best way to check if something is an array:
var something = []
something instanceof Array // true
Alternatively you can use the constructor
property as well but you need to make sure it’s not undefined
or null
:
(
something && // make sure it's not `undefined` or `null`
typeof something === 'object' && // make sure it's not a string or number
something.constructor === Array
)
Now what about an object?
So you might be thinking about using instanceof
here:
var something = {}
something instanceof Object // true
However this can be inconsistent as well:
var something = []
something instanceof Object // true
The best bet is to use constructor
(be sure to make similar checks like array above):
var something = {}
something.constructor === Object