How To Check Data Types in JavaScript using typeof

How To Check Data Types in JavaScript using typeof

The typeof keyword is used to differentiate primitive types in JavaScript. It will return one of nine strings: undefined, object (meaning null), boolean, number, bigint, string, symbol, function, or object (meaning any object, including arrays).

Image for postPhoto by Mr Cup / Fabien Barral on Unsplash

The typeof operator is useful because it is an easy way to check the type of a variable in your code. This is important because JavaScript is a dynamically typed language. ? freeCodeCamp

The typeof statement is really useful in JavaScript for data validation and type checking, but it has some odd features to be aware of.

Specifically, there are two instances when typeof returns “object” in an unexpected way, and this makes type checking a little unusual.

Both typeof null and typeof an array return “object” in a potentially misleading way, as null is a primitive type (not an object), and arrays are a special, built-in type of object in JavaScript.

In this article, I examine every possible result of typeof in JavaScript.

Image for postPhoto by Alex Read on Unsplash

Data Types

While there are only eight data types (seven primitives and objects) in JavaScript, typeof will actually return one of nine options:

  1. undefined
  2. object (meaning null)
  3. boolean
  4. number
  5. bigint
  6. string
  7. symbol
  8. function
  9. object (meaning any object, including arrays)

These correspond to the JavaScript data types, with the exception that the typeof null is also “object” due to a long-standing bug.

Next, I explain when to expect each response from typeof in detail.

Image for postPhoto by Julia Margeth Theuer on Unsplash

Undefined

An undefined value in JavaScript is pretty common ? it means a variable name has been reserved, but no value has been assigned to that reference yet. It is not defined yet, so we call it undefined.

The value undefined is a primitive type in JavaScript, and undeclared variables are also considered to be undefined.

Referencing undeclared variables usually results in a ReferenceError, except when using the typeof keyword.

The typeof undefined is the string “undefined” ? and undefined is a falsy value that is loosely equal to null but not to other falsy values.

Thus, if typeof says a value is “undefined”, then it is a safe bet to assume that value is actually undefined ? meaning it was not declared, declared but never assigned a value, or declared and assigned the value of undefined.

Image for postPhoto by Samuel Zeller on Unsplash

Object (meaning null)

For historical reasons, the typeof null in JavaScript is “object”. This is a bug that is expected to never be fixed in JavaScript.

That means that checking for null cannot be performed using typeof.

However, null checking is pretty easy using the strict equality operator (===) to check that the value is indeed null, as in maybeNull===null.

Useful things to know about null

  1. The value null is falsy (evaluates to false in a conditional).
  2. The values null and undefined are only loosely equal to each other.
  3. Neither null nor undefined are equal to other falsy values.

This means that checking for null using the loose equality (==) operator will capture both null and undefined values, which can be useful:

Often, an undefined value means the same thing as a null value ? the absence of a value, so using == is recommended to check for null.

On the other hand, checking for null can be performed easily with the strict equality === operator.

Or one can check by knowing that since the empty object is truthy (evaluates to Boolean true in a conditional), null is the only falsy object.

Image for postPhoto by Obi Onyeador on Unsplash

Boolean

Checking for Boolean values is easy ? they are going to be either true or false, and the typeof a boolean returns “boolean”:

Note that JavaScript will coerce any value to true or false by using the Boolean() wrapper function, which puts two exclamation points (the logical NOT ? !) in front of the expression. Or it?ll put the statement inside of a conditional, such as an if statement, question mark ? operator, or loop.

The values that evaluate to false are called the falsy values, and everything else in JavaScript evaluates to true (and thus is a truthy value).

The falsy values in JavaScript are false, 0, 0n, null, undefined, NaN, and the empty string ??; everything else is truthy.

Image for postPhoto by Andrik Langfield on Unsplash

Number

Checking for a number in JavaScript works as expected, with typeof returning “number”:

Note that this means that checking for NaN requires checking for self-equality because NaN is the only value in JavaScript that doesn?t equal itself:

Image for postPhoto by Kai Gradert on Unsplash

BigInt

?BigInt is a built-in object that provides a way to represent whole numbers larger than 253 – 1, which is the largest number JavaScript can reliably represent with the Number primitive. BigInt can be used for arbitrarily large integers.? ? MDN web docs

Checking for the primitive type BigInt works as expected; typeof for supported browsers will return “bigint”:

Note that BigInt is not yet part of ECMAScript, the official JavaScript standard, even though it is already supported by Chrome (and thus by Node.js), Firefox, and Edge.

?There is a good chance that BigInt will be part of ECMAScript 2019 or 2020.? ? Ralph?s Blog

Image for postPhoto by Sagar Dani on Unsplash

String

As one might hoped checking for a string in JavaScript is pretty straight-forward ? typeof works exactly as expected, returning “string”:

It sure is nice when things work like they should when programming!

Image for postPhoto by Mr Cup / Fabien Barral on Unsplash

Symbol

The primitive data type symbol is a unique identifier, useful for creating keys on objects in JavaScript.

?A symbol value may be used as an identifier for object properties; this is the data type?s only purpose.? ? MDN web docs

As one would expect, the typeof Symbol() is indeed “symbol”:

Image for postPhoto by Shahadat Shemul on Unsplash

Function

Functions are easily checked for using the typeof keyword, which works entirely as expected by returning “function”:

Image for postPhoto by Dane Deaner on Unsplash

Object (Meaning Object or Array)

As long as the value in question is not null, typeof returning “object” means that the JavaScript value is a JavaScript object.

One type of object that is built-in to JavaScript is the array, and the typeof of an array is “object”: typeof === `object` // true.

ECMAScript 5 introduced an Array.isArray() method to check for an array, since typeof will not be able to tell arrays from other objects.

The JavaScript prototypes Date and RegExp are two other types of built-in objects where typeof returns ?object.? Thus, dates and regular expressions need more differentiation than just using the typeof keyword.

I demonstrates how to check the type of objects and arrays in this code:

The verbose JavaScript statement Object.prototype.toString.call() can differentiate between generic objects, arrays, and other objects, because it returns a string that specifies the object type in more detail than typeof.

Author Moon describes that method in more detail in Better Programming:

What Is [object Object] in JavaScript: Object.prototype.toString

A deeper explanation of [object Object]

medium.com

Similarly, the helper method Array.isArray() or the keyword instanceof can be used to check for arrays or any type of object, respectively.

Image for postPhoto by Amador Loureiro on Unsplash

Watch Out for the ?Gotcha!?

The object wrappers for Boolean, number, and string will break typeof and result in “object” instead of “boolean”, “number”, or “string”.

Why do these object wrappers exist if they should not be called explicitly?

?JavaScript promptly coerces between primitives and objects.? ? Kiro Risk in JavaScript Refined

Basically, calling a string property like “”.length results in JavaScript making a wrapper object and interpreting the code this way:

Since that happens automatically, there is no need for creating an explicit wrapper object, as it will only break typeof, as shown above.

Image for postPhoto by Midas Hofstra on Unsplash

One More Reason to Not Use Wrapper Objects

Similarly, wrapper objects change the function of the == and === equality operators in JavaScript.

And the behavior only actually changes when the new keyword is used with the object wrapper call, as is shown in the following example:

Generally speaking, the string, Boolean, and number wrappers will be called automatically and should not be called by JavaScript developers.

Image for postPhoto by Marcus dePaula on Unsplash

Wait, What About Host Objects?

Host objects are implementation-dependent, meaning they are supplied by the local run-time environment.

Put another way, host objects are special objects beyond the standard built-in objects or native objects provided by JavaScript.

For example, the window object is supplied by the browser-environment supplies, while a node.js environment supplies other host objects.

This means that the typeof keyword is also implementation-dependent, at least in the case of host objects.

That being said, modern implementations are probably going to return ?object? as the typeof host objects. For example:

Image for postPhoto by Hannes Wolf on Unsplash

Are Static Types the Future?

Since JavaScript is a dynamically typed language but typeof has its quirks, some developers prefer automatic or static type checking using a language like TypeScript or a static type checker like Flow.

Using TypeScript or Flow definitely has some advantages and can prevent bugs, but at the cost of learning and implementing another tool.

While useful, using either TypeScript or Flow will add a whole new layer of complexity to your JavaScript programming.

For vanilla JavaScript, mastering typeof is all you really need in order to check data types like a champion.

Image for postPhoto by Samuel Ramos on Unsplash

The Wrap Up

The keyword typeof is useful for type checking in JavaScript, but it has some caveats associated with historical bugs.

Type checking with typeof is especially useful for most of the primitive types in JavaScript, including undefined, string, and number.

On the other hand, Array, Date, and Regular Expressions are native objects that are not differentiated from each other by typeof ? they all return “object” ? as does null, unexpectedly (in a well-known bug).

In short, typeof is an imperfect but powerful tool to check a value?s type.

Image for postPhoto by Raphael Schaller on Unsplash

Further Reading

  • Hugo Di Francesco explores checking for arrays at Code with Hugo:

JavaScript array type check ? ?is array? vs object in-depth Code with Hugo

Examples for this section at observablehq.com/@hugodf/javascript-array-detection-using-array-isarray, you can play?

codewithhugo.com

  • Tania Rascia wrote a guide to JavaScript data types in SitePoint:

A Beginner’s Guide to JavaScript Variables and Datatypes – SitePoint

A Beginner’s Guide to JavaScript Variables and Datatypes was peer reviewed by Scott Molinari and Vildan Softic and?

www.sitepoint.com

  • Webbjocke published a great article about a better way to check types, with a detailed example for every data structure in JavaScript:

How to better check data types in javascript – Webbjocke

To check what data type something has in javascript is not always the easiest. The language itself provides an operator?

webbjocke.com

  • Ashley Robinson created tables on JavaScript types at PrepScholar:

What Is the JavaScript TypeOf Function? How Does It Work?

We’ve all stumbled on a web page that just doesn’t work. You know the type: the links aren’t clickable, the scrolling?

blog.prepscholar.com

  • The static type checker Flow has a similar typeof keyword, but the version in Flow is more powerful according to the official Flow docs:

Typeof Types | Flow

Getting the internal type of a value

flow.org

Image for postPhoto by Susan Yin on Unsplash

1

No Responses

Write a response