How to use typeof with Numbers

May 3, 2021

The typeof operator returns a string that contains the primitive type of the given variable. When using this operator with numbers, it can return a few possibilities. If you are using it with the number primitive, it will return 'number'.

let x = 42;
typeof x; // 'number'

If you use it with an instance of the Number class, it will return 'object'.

let x = Number(42);
typeof x; // 'object'

Another primitive that is related to number is the BigInt primitive. typeof will treat these two primitives separately because they are two different primitives.

let x = 42n;
typeof x; // 'bigint'

NaNs

Using typeof to check whether a value is a valid number as a caveat. NaN is tricky because, even though it is an acronym for "Not a Number", typeof returns 'number' for NaN.

typeof NaN; // 'number'

To check for a valid number, you must use a combination of typeof and Number.isNaN():

let x = 42;
if (typeof x === 'number' && !Number.isNaN(x)) {
  x = 12;
}
x; // 12

Number.isSafeInteger()

JavaScript has a Number.isSafeInteger() function that neatly handles checking if a value is an integer, including checking that the value is not NaN.

Number.isSafeInteger(42); // true
Number.isSafeInteger(0); // true
Number.isSafeInteger(-1);

Number.isSafeInteger(3.14); // false
Number.isSafeInteger('42'); // false
Number.isSafeInteger(null); // false
Number.isSafeInteger(NaN); // false

If you want to check whether a value is a valid integer, Number.isSafeInteger() is the right choice. The only downside is that Internet Explorer does not support Number.isSafeInteger(), so you may need a polyfill if you support legacy browsers.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!