by Sai gowtham

How to check if a variable is a Number in JavaScript

In this tutorial, we are going to learn about two different ways to check if a given is a number in JavaScript.

typeof operator

The typeof operator will return the type of a given variable in string format, so that we can use it with if conditional to check for a number.

Example:

let a = 11;

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

Number.isInteger() method

The Number.isInteger() method returns true if a provided variable is a number, otherwise it returns false.

let a = 11;
let b = "king";

if (Number.isInteger(a)) {
  console.log('a is number');
} else {
  console.log('a is not a number');
}

// it logs not a number

if (Number.isInteger(b)) {
  console.log('b is number');
} else {
  console.log('b is not a number');
}

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