Does anyone know how can I check whether a variable is a number or a string in JavaScript?
36 Answers
Created a jsperf on the checking if a variable is a number. Quite interesting! typeof actually has a performance use. Using typeof for anything other than numbers, generally goes a 1/3rd the speed as a variable.constructor since the majority of data types in javascript are Objects; numbers are not!
http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number
typeof variable === 'number'| fastest | if you want a number, such as 5, and not '5'
typeof parseFloat(variable) === 'number'| fastest | if you want a number, such as 5, and '5'
isNaN() is slower, but not that much slower. I had high hopes for parseInt and parseFloat, however they were horribly slower.
Comments
Efficiency test
I know which way I'll be using...
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
function isNumberRE(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }
function test(fn, timerLabel) {
console.time(timerLabel)
for (i = 0; i < 1000000; i++) {
const num = Math.random() * 100
const isNum = fn(num)
}
console.timeEnd(timerLabel)
}
test(isNumber, "Normal way")
test(isNumberRE, "RegEx way")
Normal way: 25.103271484375 ms
RegEx way: 334.791015625 ms
Comments
Like others, I'm addicted to strong typing (even though I love JS)
And in my code, I happened to need to make a distinction between a number and a string, to perform 2 very different types of operations.
Rather than a spiel log:
let int = 123, str = '123';
console.log( int.constructor===Number, str.constructor===String ); // true true
console.log( typeof int === 'number', typeof str === 'number'); // true false
console.log (Number(int)===int, Number(str)===str ) // true false
// or :
console.log (String(int)===int, String(str)===str ) // false true
// the shortest :
console.log( +int===int, +str===str ); // true false
I therefore mainly use, especially in ternary tests.
let res = (+X===X) ? stuff_to_do_with_a_Number(X) : stuff_to_do_with_a_String(X);
Of course, this must be handled with care.
Comments
The best way to check types in JavaScript is the syntax typeof value ==== 'string', and a case statement may be eloquent here:
let value = 'foo';
switch(typeof value) {
case 'string':
console.log("Its a string!");
break;
case 'number':
console.log("Its a number!");
break;
}
Here is an example using the ternary operator from my linearid npm package for generating 64 and 128-bit unique IDs without generating random numbers at runtime. In this example, I check if it's not a string and convert the number or bigint to a string:
// Pads a binary string with leading zeros aligned to a bit boundary.
// @warning Does not check if the value string is not a binary string.
export function BinaryPad(value: string | number | bigint | undefined,
bit_count: number = 64, prefix: string = '0b',
pad: string = '0') {
if(bit_count <= 0) return '';
const str = (typeof value === 'string')
? String(value)
: value == undefined
? ''
: value.toString(2);
if(bit_count < str.length) {
if (bit_count < 3) return prefix + '.'.repeat(bit_count);
return prefix + str.substring(0, bit_count - 3) + '...';
}
return prefix + pad.repeat(bit_count - str.length) + str;
}
Alternatively, starting in TypeScript 5.3 you can use the switch(true) syntax:
function Foo(value: unkown) {
switch(true) {
case typeof value === 'number': return value;
case typeof value === 'string': return value;
}
}
4 Comments
+('5' || 0). The plus operator before the string forces it into a number if it can. We add the || 0 to short circuit the + operator from throwing an error on null/undefined values.
typeof myVar === 'number'/typeof myVar === 'string'. No need for any other package