How to Check if a Value is a Number in JavaScript

Understanding how to accurately determine if a value is a number is crucial in JavaScript due to the language’s type coercion and dynamic nature. We explore several methods to perform this check reliably.

Using typeof

The typeof operator is the most straightforward way to check if a value is a number:


if (typeof value === 'number') {
    console.log('Value is a number');
}
            

However, note that typeof can return ‘number’ even for NaN and Infinity.

Using isNaN

The isNaN function determines whether a value is NaN (Not a Number). It’s often used in conjunction with typeof to ensure a value is a number:


if (typeof value === 'number' && !isNaN(value)) {
    console.log('Value is a number');
}
            

This method is more reliable for filtering out NaN values.

Using Number.isFinite

Introduced in ECMAScript 6, Number.isFinite is a reliable way to check if a value is a number and is finite:


if (Number.isFinite(value)) {
    console.log('Value is a finite number');
}
            

This method does not coerce types, providing a stricter check compared to the global isFinite function.

Leave a Reply

Your email address will not be published. Required fields are marked *