Photo by Jenna Hamra from Pexels

Dealing with data types is a common task in basically any programming language, be it dynamic or static, weakly typed or strongly typed. JavaScript is no exception. Have you ever needed to check the type of a variable in JavaScript? If so, you probably found out that some checks can be trickier than what you expect. In this article, we are going to see how to check for several data types in JS. Just keep reading!

Data types and JavaScript

First, let’s briefly discuss the concept of data type, or at least what we mean by data type in this article, in the context of JavaScript. While this concept is historically one of the most debated topics in computer science, our interpretation of data type here is extremely practical and non-academic. In this article, things like objects, arrays (which are objects), functions (also objects), numbers, NaN (which are numbers) and others will be treated as distinct types. So, if you have an academic background or are really strict when it comes to typing systems, relax and don’t take this concept too seriously for now.

Strings

Strings are primitive values and testing them is really straightforward. You just need to use the typeof operator:

function printMessage(message) { if (typeof message !== 'string') { return; } // ... }

Really simple, isn’t it? However, there is a special case where this expression would evaluate to false: if the string is initialized using the String constructor directly.

const message = new String('This will not work'); console.log(typeof message); //=> "object"

Dealing with string objects is definitely uncommon and creating them is not recommended. If you need to create a string, always favor the literal syntax. The String constructor is used under the hood by the engine to create wrapper objects. You don’t need to use them directly. However, if for some reason, you need to ensure that a given value is a string, be it primitive or an object, you can combine the instanceof and typeof operators:

const isString = value => typeof value === 'string' || value instanceof String; const message1 = 'This is a string primitive'; const message2 = new String('This is a string object'); console.log(isString(message1)); //=> true console.log(isString(message2)); //=> true

Null and undefined

In JavaScript, null and undefined are often mistaken for each other. In simple words, undefined is the default value for uninitialized variables and null is always explicitly set to a variable.

If you use the typeof operator against both, this is what you get:

console.log(typeof undefined); //=> "undefined" console.log(typeof null); //=> "object"

Well, we got “undefined” for undefined. That makes sense. However, JavaScript gave us “object” as the type for null. This is not by design. It’s an old bug, dating back to the original language implementation. This bug was never fixed, since a considerable part of current JS codebase (which is huge) would break if typeof null suddenly started evaluating to “null”.

To test for null or undefined, you can just use the strict equality operator (===):

if(a === undefined) {} if(a === null) {}

If you want to check whether a variable is either null or undefined, you could, of course, combine the two tests above (a === undefined || a === null). However, there’s a more succinct way of doing so, by using the abstract equality operator (==):

if (a == null) {}

The above expression evaluates to true only if a is null or undefined. Some people try to find the logic behind this behavior, arguing that since null and undefined are falsy values, both would be equal if compared with the abstract equality operator. This does not make sense, since other falsy values like 0 (zero), “” (empty string) or NaN, when compared to null or undefined, will not result in an equality.

console.log(null == ''); //=> false console.log(null == NaN); //=> false console.log(null == 0); //=> false console.log(undefined == ''); //=> false console.log(undefined == NaN); //=> false console.log(undefined == 0); //=> false

The fact is that there is no real logic behind this. It only happens because ECMAScript specification states so (just check the second and third points of section 11.9.3).

Arrays

Arrays are objects. If you try to use the typeof operator against an array, you’ll get “object” as result. The right way to check if a variable is an array is by using the Array.isArray() static method (IE9+):

Array.isArray(someVar); Array.isArray([11, 22, 33]); //=> true Array.isArray({}); //=> false

Function

Functions are also objects. However, differently from arrays, it is possible to check for functions by using the typeof operator:

const f = function() {}; console.log(typeof f === 'function'); //=> true

Objects

To check if a variable is an object, you can compare it against its “boxed” equivalent. If both are equal, it means that your variable is already an object. Please have in mind that this will evaluate to true for any kind of object, including arrays and functions:

const a = {}; console.log(a === Object(a)); //=> true const b = []; console.log(b === Object(b)); //=> true const c = function() {}; console.log(c === Object(c)); //=> true const d = 123; console.log(d === Object(d)); //=> false const e = ''; console.log(e === Object(e)); //=> false

Numbers and Booleans

Numbers and Booleans are really similar to Strings in terms of type testing. Most of the time, you just need to use typeof:

if (typeof a === 'string') {} if (typeof b === 'boolean') {}

But, in case you need to test for wrapper objects as well and not only primitive values, you could combine typeof and instanceof:

const isBoolean = value => typeof value === 'boolean' || value instanceof Boolean; const isNumber = value => typeof value === 'number' || value instanceof Number;

NaN, Infinity and -Infinity

If you use typeof against NaN (the acronym for Not a Number), Infinity (JavaScript’s positive infinite number) or -Infinity (negative infinite number), you’ll get “number” as result. I know that it looks weird at first glance, but according to ECMAScript specification, the Number type includes these special numeric values. In order to check for these values, you can use specific builtin functions:

if (isNaN(value)) {} // Checks if value is NaN if (!isFinite(value)) {} // Checks if value is Infinity or -Infinity

Or, if you need to test if a variable is specifically positive or negative infinity:

if (value === Number.POSITIVE_INFINITY) {} // Checks if value is Infinity if (value === Number.NEGATIVE_INFINITY) {} // Checks if value is -Infinity

Conclusion

In JavaScript, different data types require distinct forms of checking.

Strings, numbers, booleans and functions can be easily checked by using the typeof operator.

For null and undefined, you can use a simple comparison with the strict equality operator.

Arrays can be recognized by using the Array.isArray static method

You can check objects of any kind by comparing them with their boxed value

We have special functions such as isNaN and isFinite, for us to check numeric values like NaN, Infinity and -Infinity

Do you want to become a JavaScript master? If so, you need to check out Mosh’s JavaScript course. It’s the best JavaScript course out there! And if you liked this article, share it with others as well!

Like this: Like Loading...

Related

Tags: Data Types