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:
JAVASCRIPTconst number = 1;
const type = typeof number;
console.log(type);
BASHnumber
That's pretty straightforward and expected. However, watch what happens when we use the typeof
operator on an object of type Number:
JAVASCRIPTconst number = 1;
const object = new Number(1);
const type = typeof object;
console.log(type);
BASHobject
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:
JAVASCRIPTconst bigInt = BigInt(1);
const type = typeof bigInt;
console.log(type);
BASHbigint
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:
JAVASCRIPTconst 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!
- Getting Started with Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications