How to find type of number in JavaScript?

Table of Contents

Introduction

In JavaScript, determining the type of a value is essential for validating input and controlling logic flow. You can easily find out whether a variable or value is a number using the built-in typeof operator. There are also other methods to check if a value is a number, including Number.isFinite() and isNaN(). Let's explore how to find the type of a number in JavaScript and when to use each approach.

Using typeof to Find the Type of a Number

1. The typeof Operator

The typeof operator is a straightforward way to check if a value is a number. It returns a string indicating the type of the operand. For numbers, it returns "number".

Example 1: Checking a Number Type

Example 2: Checking a Floating-Point Number

Note: In JavaScript, both integers and floating-point numbers are categorized as the number type.

2. Using Number.isFinite() for Finite Numbers

If you need to ensure that the value is a number and is finite, you can use Number.isFinite(). This method returns true only for finite numbers, excluding NaN, Infinity, and -Infinity.

Example 3: Using Number.isFinite()

3. Checking if a Value is NaN

Sometimes you may want to check if a value is NaN (Not-a-Number). This can happen when mathematical operations fail or incorrect input is processed.

Example 4: Using isNaN() and Number.isNaN()

isNaN() checks if a value is not a number, while Number.isNaN() specifically checks if the value is the NaN type.

Additional Methods for Type Checking

1. Checking with typeof for Edge Cases

In JavaScript, certain values may behave differently than expected. For instance, null is not a number but returns "object" when checked with typeof. Similarly, arrays and objects may behave unexpectedly when using typeof.

Example 5: Avoiding Common Mistakes

2. Differentiating Between number and Other Types

To ensure that a variable is specifically a number (and not a string that looks like a number), it's important to validate both type and value.

Example 6: Strict Validation Using typeof

Conclusion

In JavaScript, finding the type of a number is easy using the typeof operator. For more advanced checks, you can use Number.isFinite() to ensure the value is a finite number or isNaN() to check for invalid numbers. By understanding these methods, you can handle different types of numeric input and values effectively, making your code more robust and error-free.

Similar Questions