580

Does anyone know how can I check whether a variable is a number or a string in JavaScript?

2
  • stackoverflow.com/questions/18082/… Commented Oct 7, 2011 at 16:33
  • typeof myVar === 'number'/typeof myVar === 'string'. No need for any other package Commented Sep 20, 2024 at 0:40

36 Answers 36

1
2
0

Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.

return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
Sign up to request clarification or add additional context in comments.

Comments

0

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

0

What do you thing about this one?

const numberOrString='10' 
const isNumber = !isNaN(numberOrString*1) 

Comments

0

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

0

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

0

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

typeof NaN will actual return 'number'. So this does not work. Don't ask me why Javascript returns 'number' on NaN.
I'm not sure I'm following you. Is it not working my linearid library and I bozoed it? I'm just confused why NaN being a number makes the solution I know to be working not work.
At least my answer had the updated TypeScript syntax and three different ways to do it. I think it's best answer for this reason, which was also why I took my engineering resources to write it.
I think there's a lot more to the question. For example, what if the string is '5'? In most cases, you actually do want it to return as a number. The simplest way to do that is the following +('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.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.