Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, I’m going to show how you check if a string is a number in javascript, here I will use the javascript isNaN() built-in method to check string is a valid number or not.

The isNaN() function determines whether a value is NaN (Not a number ) or not. Because coercion inside the isNaN function can be surprising, you may alternatively want to use Number.isNaN().

Let’s start today’s tutorial How to check if a string is a number in javascript?

First, let’s understand how the isNaN() method behaves, and what it returns in different input types.

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true
isNaN('')          // false
isNaN(' ')         // false
isNaN(false)       // false

Understing the above one thing is clear, the isNaN() returns true if it’s string input.

So, what we will do.

  1. Create a sample num string variable
  2. Use isNaN() method to check valid number or not.
  3. Console message if it’s a number
// Create a sample num string variable
const numStr = "22";

// Use `isNaN()` method to check valid number or not.
if(!isNaN(numStr)){
  // Console message if it's a number
  console.log("numStr is a valid number");
}

When running the above program it should console numStr is a valid number in the log. let’s check the output.

javascript, check if a string is a number example
javascript, check if a string is a number example

I hope it’s help you, All the best 👍.