search
HomeWeb Front-endJS Tutorial3 ways to determine whether a variable is a number in JavaScript (with code)

3 ways to determine whether a variable is a number in JavaScript (with code)

Recommended tutorial: "JavaScript Video Tutorial"

JavaScript is a dynamically typed language, which means that the interpreter is runtimeDetermine the type of the variable. In fact, this also allows us to use the same variable to store different types of data in the same code. Without documentation and consistency, we don't always know the type of a variable when working with code.

When we expect a variable to be a number, operating on strings or arrays can lead to strange results in the code. In this article, we will introduce some functions that determine whether a variable is a number.

Strings of numbers like "10" should not be accepted. In JavaScript, special values ​​such as NaN, Infinity, and -Infinity are also of numeric type.

Based on these requirements, the best function to use is the isFinite() function in the built-in Number object. However, developers often use other functions such as the Number.isNaN() and typeof() functions.

Let’s create some variables first:

let intVar = 2;
let floatVar = 10.5;
let stringVar = '4';
let nanVar = NaN;
let infinityVar = Infinity;
let nullVar = null;
let undefinedVar = undefined;

Use Number.isFinite() function name

Number. The isFinite() function checks whether the variable is a number and also checks whether it is a finite value. So for numbers of NaN, Infinity, or -Infinity, it returns false.

Let’s check it using the variables defined above:

> Number.isFinite(intVar);
true
> Number.isFinite(floatVar);
true
> Number.isFinite(stringVar);
false
> Number.isFinite(nanVar);
false
> Number.isFinite(infinityVar);
false
> Number.isFinite(nullVar);
false
> Number.isFinite(undefined);
false

This is exactly what we want. Special non-finite numbers and any variable of non-numeric type are ignored. So, if you want to check if a variable is a number, the best way is to use the Number.isFinite() function.

Use the Number.isNaN() method

The standard Number object has a isNaN()method. It accepts a parameter and determines whether its value is NaN. Since we want to check if a variable is a number, we will use the not operator ! in the check.

> !Number.isNaN(intVar);
true
> !Number.isNaN(floatVar);
true
> !Number.isNaN(stringVar);
true # Wrong
> !Number.isNaN(nanVar);
false
> !Number.isNaN(infinityVar);
true # Wrong
> !Number.isNaN(nullVar);
true # Wrong
> !Number.isNaN(undefinedVar);
true # Wrong

This method is quite permissive as it accepts values ​​that are not numbers at all. This approach works best when you know you have a number and want to check if it is a NaN value, rather than a general number check.

Use typeof() method

typeof()The function is a global function that accepts a variable or value as parameter and returns a string representation of its type. JavaScript has a total of 9 types

  • undefined
  • boolean
  • number
  • string
  • bigint
  • symbol
  • object
  • null (typeof() displays object)
  • function (a special type of object )

To verify whether the variable is a number, we only need to check whether the value returned by typeof() is `"number". Let's try it with a test variable:

> typeof(intVar) == 'number';
true
> typeof(floatVar) == 'number';
true
> typeof(stringVar) == 'number';
false
> typeof(nanVar) == 'number';
true # Wrong
> typeof(infinityVar) == 'number';
true # Wrong
> typeof(nullVar) == 'number';
false
> typeof(undefined) == 'number';
false

typeof() The performance of the function is much better than Number.isNaN(). It correctly determines that the string variables null and undefined are not numbers. However, for NaN and Infinity, it returns true.

Although this is technically the correct result, NaN and Infinity are special numeric values ​​and for most use cases we prefer to ignore them.

Summary

#In this article, we learned how to check if a variable is a number in JavaScript. The Number.isNaN() function only applies when we know the variable is a number and need to verify whether it is NaN`.

If there are NaN, Infinity or -Infinity and other numbers in the code, the typeof()` function is applicable.

Number.isFinite()The method captures all finite numbers and is the most suitable for our requirements.

Original address: https://stackabuse.com/javascript-check-if-variable-is-a-number/

Author: Marcus Sanatan

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of 3 ways to determine whether a variable is a number in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software