


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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In a MySQL database, gender fields can usually be stored using the ENUM type. ENUM is an enumeration type that allows us to select one as the value of a field from a set of predefined values. ENUM is a good choice when representing a fixed and limited option like gender. Let's look at a specific code example: Suppose we have a table called "users" that contains user information, including gender. Now we want to create a field for gender, we can design the table structure like this: CRE

In MySQL, the most suitable data type for gender fields is the ENUM enumeration type. The ENUM enumeration type is a data type that allows the definition of a set of possible values. The gender field is suitable for using the ENUM type because gender usually only has two values, namely male and female. Next, I will use specific code examples to show how to create a gender field in MySQL and use the ENUM enumeration type to store gender information. The following are the steps: First, create a table named users in MySQL, including

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

Detailed explanation of how to use Boolean types in MySQL MySQL is a commonly used relational database management system. In practical applications, it is often necessary to use Boolean types to represent logical true and false values. There are two representation methods of Boolean type in MySQL: TINYINT(1) and BOOL. This article will introduce in detail the use of Boolean types in MySQL, including the definition, assignment, query and modification of Boolean types, and explain it with specific code examples. 1. The Boolean type is defined in MySQL and can be

jQuery is a JavaScript library widely used in web development. It provides many simple and convenient methods to operate web page elements and handle events. In actual development, we often encounter situations where we need to determine whether a variable is empty. This article will introduce several common methods of using jQuery to determine whether a variable is empty, and attach specific code examples. Method 1: Use the if statement to determine varstr="";if(str){co

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint
