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:
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 TypeScript
- Getting Started with Express
- Create an RSS Reader in Node
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript