Question 7
Question
Can you explain how to use Number.isFinite(), Number.isNaN(), and Number.isInteger() for type checking?
Answer
Those methods are essential tools in JavaScript when dealing with numbers, allowing you to accurately check their types and properties.
Here's a breakdown of each:
1. Number.isFinite(number)
Purpose: Determines if a value is a finite number (a normal number that doesn't include infinity or NaN).
Return Value: Returns
trueif the value is a finite number, andfalseotherwise.Example:
console.log(Number.isFinite(5)); // Output: true console.log(Number.isFinite(Infinity)); // Output: false console.log(Number.isFinite(-10.5)); // Output: true console.log(Number.isFinite('hello')); // Output: false
2. Number.isNaN(number)
Purpose: Checks if a value is NaN (Not a Number), which represents an undefined or unrepresentable numerical value.
Return Value: Returns
trueif the value is NaN, andfalseotherwise.Example:
console.log(Number.isNaN(NaN)); // Output: true console.log(Number.isNaN(123)); // Output: false console.log(Number.isNaN('hello')); // Output: true console.log(Number.isNaN(Infinity)); // Output: false
3. Number.isInteger(number)
Purpose: Determines if a value is an exact whole number (an integer). It doesn't consider fractions or decimals.
Return Value: Returns
trueif the value is an integer, andfalseotherwise.Example:
console.log(Number.isInteger(5)); // Output: true console.log(Number.isInteger(3.14)); // Output: false console.log(Number.isInteger(-7)); // Output: true
Why Use These Methods?
Robustness:
Number.isFinite(),Number.isNaN(), andNumber.isInteger()provide reliable type checks that handle various edge cases better than simply usingtypeofor direct comparisons.
Last updated