by Sai gowtham

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

In the above code, we are getting false if a variable has a value string number '3', But we need true to do this we need to create our own 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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course