JavaScript Code


How to check if given number is finite in JavaScript?


Check if given number is finite in JavaScript

Given a number, write a JavaScript program to check if this number is finite or not.

Solution

To check if given number is finite, call isFinite() global function and pass the number as argument. The function returns true if the number is finite, or false if not.

isFinite(n)

Programs

1. Check if the number in n is finite.

var n = 25;
if ( isFinite(n) ) {
    console.log('n is finite');
} else {
    console.log('n is not finite');
}

2. Take an expression of integer divided by zero in n , and programmatically check if the number n is finite.

var n = 3 / 0;
if ( isFinite(n) ) {
    console.log('n is finite');
} else {
    console.log('n is not finite');
}

3. Take infinity in n, and programmatically check if the number n is finite.

var n = Infinity;
if ( isFinite(n) ) {
    console.log('n is finite');
} else {
    console.log('n is not finite');
}