Assorted
typeof bar === "object"
to determine if bar
is an object
typeof bar === "object"
to determine if bar
is an objecttypeof bar === "object"
is a reliable way of checking if bar
is an object
But:null
is also considered an object!
Therefore:
var bar = null;
console.log(typeof bar === "object"); // logs true!
Solution: also check if bar
is null
:
console.log((bar !== null) && (typeof bar === "object"));
// logs false
There are two other things worth noting:
First, the above solution will return false
if bar
is a function. In most cases, this is the desired behavior, but in situations where you want to also return true
for functions, you could amend the above solution to be:
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true
if bar
is an array (e.g., if var bar = [];
). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false
for arrays, you could amend the above solution to be:
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
However, there’s one other alternative that returns false
for nulls, arrays, and functions, but true
for objects:
console.log((bar !== null) && (bar.constructor === Object));
Or, if you’re using jQuery:
console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));
ES6 makes the array case quite simple, including its own null check with Array.isArray():
console.log(Array.isArray(bar));
NaN
Definition
Represents a value that is not a number.
Results from an operation that could not be performed.
Gotchas
Although
NaN
means “not a number”, its type is, believe it or not,Number
:
console.log(typeof NaN === "number"); // logs "true"
2. NaN
compared to anything – even itself! – is false:
console.log(NaN === NaN); // logs "false"
Testing whether a number is equal to NaN
built-in function isNaN()
(imperfect solution)
value !== value
only true if the value is NaN
More reliable solution: ES6 Number.isNaN()
function
Last updated