by Sai gowtham

How to check if a variable is a number in JavaScript

Home » javascript » How to check if a variable is a number in JavaScript

In this tutorial, we are going to learn about how to check if a variable (including a string) is a number in JavaScript.

JavaScript has a built-in isNan() function where it returns false if a given variable is a number else it returns true (if a given variable is not a number).

Example:

const num = 3;

console.log(isNaN(num)); // false

const strNum = '3';

console.log(isNaN(strNum)); // false


const str = 'react';

console.log(isNaN(str)); // true

But we need true if our given variable is a number or string number to do this we need to create our function called isNumeric.

function isNumeric(num){
    return !isNaN(num); // added negation operator
}

console.log(isNumeric('3')); // true

console.log(isNumeric(3)); // true

console.log(isNumeric('fabric')) // false