Explain Codes LogoExplain Codes Logo

Check whether variable is number or string in JavaScript

javascript
type-checking
javascript-features
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 20, 2024
TLDR

Quickly identify number and string types using JavaScript's typeof operator:

let varNum = 42, varStr = "hello"; let isNumber = typeof varNum === 'number'; // true if number, false if impostor let isString = typeof varStr === 'string'; // true if string, false if masquerading

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:

let isTrueString = Object.prototype.toString.call(varStr) === '[object String]'; // working the S in SOLID let isTrueNumber = Object.prototype.toString.call(varNum) === '[object Number]'; // numbers don't lie

For number validation that excludes NaN, Infinity, and -Infinity (which are technically number but often not desired), use Number.isFinite(value):

let varInfinity = Infinity; let isFiniteNumber = Number.isFinite(varNum); // true if finite number, false if tarnished medal

To identify number-like strings, you can use a regex like a seasoned coder:

let isNumericString = /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(varStr); // no scientific theory here, only reality

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:

let isNumberCasted = !isNaN(parseFloat(varStr)) && isFinite(varStr); // check, check, and mate

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

function validateInput(input) { return Number.isFinite(+input) || input.trim().length > 0; // triple-check on user action }

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:

function coerceType(value) { if (!isNaN(value) && value !== '') { return +value; // behold, the inner number } return value; }

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:

function sortByType(a, b) { let aIsNumber = typeof a === 'number'; let bIsNumber = typeof b === 'number'; if (aIsNumber && bIsNumber) { return a - b; // numbers are straighforward; they don't beat around the bush } else if (!aIsNumber && !bIsNumber) { return a.localeCompare(b); // for eloquent strings, it's all about lexicographic charm } return aIsNumber ? -1 : 1; }

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:

let isUnderscoreString = _.isString(varStr); // if you testify it's a string, underscore.js will second it!

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.