Check whether variable is number or string in JavaScript
Quickly identify number
and string
types using JavaScript's typeof
operator:
In JavaScript, typeof
simplifies type-checking—no polygraph test required.
Going beyond 'typeof'
The typeof
operator isn't always Sherlock Holmes—it has its limitations. For instance, typeof new String('asdf')
gets you 'object'
. A more reliable method for true string
and number
types involves using Object.prototype.toString:
For number
validation that excludes NaN
, Infinity
, and -Infinity
(which are technically number
but often not desired), use Number.isFinite(value)
:
To identify number-like strings, you can use a regex like a seasoned coder:
When it's not all black and white
Sometimes things in JavaScript fall in a grey zone—similar to how your cat might occasionally act like a dog. When a variable is a numeric string, or a string that decidedly looks like a number, type-casting and parseFloat()
, along with isNaN
, can aid you:
Remember, NaN
is the only value in JavaScript which doesn't keep the promise to itself—varNum !== varNum
checks if a value is actually the great pretender, NaN
.
How to handle real-world scenarios
In practical applications, often we need to differentiate between numbers and strings for efficient data processing. Let's delve into some everyday use-cases:
1. Unpacking form data
This function aids form validation—it ensures both non-empty strings and finite numbers are valid input.
2. Processing data
When parsing JSON data, strings may be masquerading as numbers. To unveil their true identity:
This function attempts to recover numeric strings to their actual glory—numbers!
3.Interpreting user inputs
How you interpret user inputs like sorting depends on their type. For instance:
Here, 'number' and 'string' values find their rightful place—in order.
Kudos to underscore.js
To make a developer's life more convenient, underscore.js offers the precise _.isString(obj)
for checking string types:
For Enumerable collections, "duck typing" helps us evaluate an object to see if it acts like a duck, i.e., checks if a supposed string quacks
as a string based on its methods or properties.
Was this article helpful?