Using typeof with Numbers in JavaScript

Updated onbyAlan Morel
Using typeof with Numbers in JavaScript

Because JavaScript is a loosely typed language, it is not always clear what type of data a variable holds.

This is why we can use the typeof operator to determine the primitive type of data that a variable is holding.

However, things are not that simple when we are working with numbers.

In this post, we'll learn about the typeof operator and how to properly use it when you're working with numbers in JavaScript.

Using the typeof operator

Let's see what the typeof operator returns when we use it on a number:

const number = 1;
const type = typeof number;

console.log(type);
number

That's pretty straightforward and expected. However, watch what happens when we use the typeof operator on an object of type Number:

const number = 1;
const object = new Number(1);
const type = typeof object;

console.log(type);
object

Because the variable is technically an object created from the Number constructor, the typeof operator returns object.

Now let's look at when we use a BigInt primitive:

const bigInt = BigInt(1);
const type = typeof bigInt;

console.log(type);
bigint

Likewise, the typeof operator returns bigint when we use it on a BigInt primitive.

How to check if a variable is an Integer

The best way to check if a variable is an integer is to just rely on the built-in Number.isSafeInteger method.

Keep in mind that this only works on integers and not floating point numbers.

Let's look at examples of how this works:

const number = 1;
const isSafe = Number.isSafeInteger(number);

console.log(isSafe);

It will properly handle checking if a variable is an integer, checking that the value is not NaN, and checking that the value is not Infinity.

Conclusion

In this post, we learned how to use the typeof operator to check if a variable is a number.

Using it can be tricky because the Number class and BigInt will not return number when you use the typeof operator. If you want to check for an integer, you'll need to use the Number.isSafeInteger method.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.