Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Check variable is number or not in Javascript

In this chapter, you will learn about how to check variable is number or not in Javascript, here I am listing the possible ways to check if the variable is number or not.

Solution 1:
isNaN(): We can use the method isNaN() to check if the value is number, the method isNaN() returns the boolean value, it returns true if the variable is not a number and returns false if the variable is a number. Let’s write an example for the same,

let num = 500;
let checkIfNumber = isNaN(num);
console.log(checkIfNumber);

if(isNaN(num)) {
  console.log('Variable num is not a number');
} else {
  console.log('Variable num is number');
}

// output
// false
// Variable num is number

Solution 2:
typeof: We can also use the typeof operator to the same, and it returns a string indicating the type of the unevaluated operand.

let num = 400;
let notanum = '400';

console.log(typeof num);
console.log(typeof notanum);

if (typeof num === 'number') {
  console.log('The variable num is a number');
} else {
  console.log('The variable num is not a number');
}

if (typeof notanum === 'number') {
  console.log('The variable num is a number');
} else {
  console.log('The variable num is not a number');
}

// output
// number
// string
// The variable num is a number
// The variable num is not a number

Solution 3:
We can define our own function and check the variable with a regular expression and return the response. Let’s write an example of the same.
Note: The below function returns true if the variable does not contain anything except the numbers, and you can pass the value with quotes.

const isVariableNumber = (num) => {
  return /^-?[\d.]+(?:e-?\d+)?$/.test(num);
}

console.log(isVariableNumber(300));
console.log(isVariableNumber('Number'));

// output
// true
// false