Jin Yong
Jin Yong

Reputation: 43768

Check whether variable is number or string in JavaScript

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

Upvotes: 578

Views: 759923

Answers (30)

Adam Sassano
Adam Sassano

Reputation: 273

With the many answers with many examples already, this answer is to show a comparison of results from the many different combinations of functions and values.

You will find almost each function returns different results using the same sample set of data. You may have to be selective to ensure the function you are using returns the results you are indeed looking for.

And of course, the functions & values objects can be further modified with your favorite different entries if not already included.

'use strict';

// Collection of test functions
const functions = {
    'constructor.name': value => !(value === undefined || value === null) ? value.constructor.name : '',
    'typeof': value => typeof value,
    'Number.isFinite': value => Number.isFinite(value),
    'isFinite': value => isFinite(value),
    '!Number.isNaN': value => !Number.isNaN(value),
    '!isNaN': value => !isNaN(value),
    'ternany': value => value ? 'true' : 'false',
    '>0': value => value > 0,
    'regexInteger': value => /^-?\d+$/.test(value),
    'regexFloat': value => /^[\-\+]?[\d]+\.?(\d+)?$/.test(value),
    '$.isNumeric()': value => !isNaN(parseFloat(value)) && isFinite(value),
    'parseFloatLoose': value => parseFloat(value) == value,
    'parseFloatStrict': value => parseFloat(value) === value,
    'divideBy0': value => value == 0 ? true : !isNaN(value / 0)
};

// Collection of sample data to send to functions
const values = {
    // Number – number
    '0': 0,
    '123': 123,
    '-123': -123,
    '123.456': 123.456,
    '1e+30': 1e+30,
    '1e+10000': 1e+10000,
    'Infinity': Infinity,
    '-Infinity': -Infinity,
    'NaN': NaN,
    'Number(123)': Number(123.4),
    "Number('123')": Number('123.4'),
    'parseInt(123)': parseInt(123.4),
    "parseInt('123')": parseInt('123.4'),
    'parseFloat(123)': parseFloat(123.4),
    "parseFloat('123')": parseFloat('123.4'),
    // Number – object
    'new Number(123)': new Number(123),
    'new Number(-123)': new Number(-123),

    // String – string
    "'0'": '0',
    "'123'": '123',
    "'-123'": '-123',
    "'123.456'": '123.456',
    "'1e+30'": '1e+30',
    "'1e+10000'": '1e+10000',
    "'Infinity'": 'Infinity',
    "'-Infinity'": '-Infinity',
    "'NaN'": 'NaN',
    "'foo'": 'foo',
    "'123px'": '123px',
    "''": '',
    "' '": ' ',
    // String – object
    'new String(-1)': new String(-1),
    'new String(123)': new String(123),
    "new String('123')": new String('123'),
    "new String('foo')": new String('foo'),

    // Boolean – boolean
    'true': true,
    'false': false,
    // Boolean – object
    'new Boolean(true)': new Boolean(true),
    'new Boolean(false)': new Boolean(false),

    // N/A – undefined
    'undefined': undefined,
    // N/A – object
    'null': null,

    // Array – object
    '[]': [],
    '[0]': [0],
    '[0,1]': [0, 1],
    "['123']": ['123'],
    'new Array': new Array,
    'new Array()': new Array(),
    'new Array(2)': new Array(2),
    "new Array('x')": new Array('x'),
    'new Object([])': new Object([]),
    'new Object([123])': new Object([123]),

    // Object – object *** Extra data to show constructor name & typeof ***
    '{}': {},
    "{foo: 'bar'}": { foo: 'bar' },
    'new Object({})': new Object({}),

    // <Class Name> - object *** Extra data to show constructor name & typeof ***
    'new class { }': new class { },
    'new class Foo { }': new class Foo { },

    // Function – function *** Extra data to show constructor name & typeof ***
    'Number': Number,
    'String': String,
    'Boolean': Boolean,
    'Array': Array,
    'Object': Object,
    'class { }': class { },
    'class Bar { }': class Bar { },
    'function() { }': function () { },
    '() => { }': () => { }
};

// Determine column width constant from longest key length in either functions or values objects, plus 2 character padding, minimum 16 character length
const columnWidth = Object.keys({ ...functions, ...values }).reduce((len, current) => Math.max(len, current.length + 2), 16);

// Presentation & padding function for each column field
const column = (value, prefix = '', suffix = '') => `${prefix}${value}${suffix}${' '.repeat(columnWidth - prefix.length - value.toString().length - suffix.length)}`;

// Output Functions List & Value Results header row
console.log(Object.entries(functions).reduce((header, [functionsKey, functionsValue]) => header = `${header.replace('\n\n', `\n${column(functionsKey, '', ':')}${functionsValue};\n\n`)}${column(functionsKey, '', ':')}`, `Functions List:\n\nValue Results:\n${column('Value:')}`));

// Output result of each value using each function
Object.entries(values).forEach(([valuesKey, valuesValue]) => console.log(Object.values(functions).reduce((results, functionsValue) => results += column(functionsValue(valuesValue), '// '), column(valuesKey))));

This will return:

Functions List:
constructor.name:   value => !(value === undefined || value === null) ? value.constructor.name : '';
typeof:             value => typeof value;
Number.isFinite:    value => Number.isFinite(value);
isFinite:           value => isFinite(value);
!Number.isNaN:      value => !Number.isNaN(value);
!isNaN:             value => !isNaN(value);
ternany:            value => value ? 'true' : 'false';
>0:                 value => value > 0;
regexInteger:       value => /^-?\d+$/.test(value);
regexFloat:         value => /^[\-\+]?[\d]+\.?(\d+)?$/.test(value);
$.isNumeric():      value => !isNaN(parseFloat(value)) && isFinite(value);
parseFloatLoose:    value => parseFloat(value) == value;
parseFloatStrict:   value => parseFloat(value) === value;
divideBy0:          value => value == 0 ? true : !isNaN(value / 0);

Value Results:
Value:              constructor.name:   typeof:             Number.isFinite:    isFinite:           !Number.isNaN:      !isNaN:             ternany:            >0:                 regexInteger:       regexFloat:         $.isNumeric():      parseFloatLoose:    parseFloatStrict:   divideBy0:
0                   // Number           // number           // true             // true             // true             // true             // false            // false            // true             // true             // true             // true             // true             // true
123                 // Number           // number           // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true
-123                // Number           // number           // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true             // true
123.456             // Number           // number           // true             // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true
1e+30               // Number           // number           // true             // true             // true             // true             // true             // true             // false            // false            // true             // true             // true             // true
1e+10000            // Number           // number           // false            // false            // true             // true             // true             // true             // false            // false            // false            // true             // true             // true
Infinity            // Number           // number           // false            // false            // true             // true             // true             // true             // false            // false            // false            // true             // true             // true
-Infinity           // Number           // number           // false            // false            // true             // true             // true             // false            // false            // false            // false            // true             // true             // true
NaN                 // Number           // number           // false            // false            // false            // false            // false            // false            // false            // false            // false            // false            // false            // false
Number(123)         // Number           // number           // true             // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true
Number('123')       // Number           // number           // true             // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true
parseInt(123)       // Number           // number           // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true
parseInt('123')     // Number           // number           // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true             // true
parseFloat(123)     // Number           // number           // true             // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true
parseFloat('123')   // Number           // number           // true             // true             // true             // true             // true             // true             // false            // true             // true             // true             // true             // true
new Number(123)     // Number           // object           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
new Number(-123)    // Number           // object           // false            // true             // true             // true             // true             // false            // true             // true             // true             // true             // false            // true
'0'                 // String           // string           // false            // true             // true             // true             // true             // false            // true             // true             // true             // true             // false            // true
'123'               // String           // string           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
'-123'              // String           // string           // false            // true             // true             // true             // true             // false            // true             // true             // true             // true             // false            // true
'123.456'           // String           // string           // false            // true             // true             // true             // true             // true             // false            // true             // true             // true             // false            // true
'1e+30'             // String           // string           // false            // true             // true             // true             // true             // true             // false            // false            // true             // true             // false            // true
'1e+10000'          // String           // string           // false            // false            // true             // true             // true             // true             // false            // false            // false            // true             // false            // true
'Infinity'          // String           // string           // false            // false            // true             // true             // true             // true             // false            // false            // false            // true             // false            // true
'-Infinity'         // String           // string           // false            // false            // true             // true             // true             // false            // false            // false            // false            // true             // false            // true
'NaN'               // String           // string           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
'foo'               // String           // string           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
'123px'             // String           // string           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
''                  // String           // string           // false            // true             // true             // true             // false            // false            // false            // false            // false            // false            // false            // true
' '                 // String           // string           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
new String(-1)      // String           // object           // false            // true             // true             // true             // true             // false            // true             // true             // true             // true             // false            // true
new String(123)     // String           // object           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
new String('123')   // String           // object           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
new String('foo')   // String           // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
true                // Boolean          // boolean          // false            // true             // true             // true             // true             // true             // false            // false            // false            // false            // false            // true
false               // Boolean          // boolean          // false            // true             // true             // true             // false            // false            // false            // false            // false            // false            // false            // true
new Boolean(true)   // Boolean          // object           // false            // true             // true             // true             // true             // true             // false            // false            // false            // false            // false            // true
new Boolean(false)  // Boolean          // object           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
undefined           //                  // undefined        // false            // false            // true             // false            // false            // false            // false            // false            // false            // false            // false            // false
null                //                  // object           // false            // true             // true             // true             // false            // false            // false            // false            // false            // false            // false            // false
[]                  // Array            // object           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
[0]                 // Array            // object           // false            // true             // true             // true             // true             // false            // true             // true             // true             // true             // false            // true
[0,1]               // Array            // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
['123']             // Array            // object           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
new Array           // Array            // object           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
new Array()         // Array            // object           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
new Array(2)        // Array            // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
new Array('x')      // Array            // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
new Object([])      // Array            // object           // false            // true             // true             // true             // true             // false            // false            // false            // false            // false            // false            // true
new Object([123])   // Array            // object           // false            // true             // true             // true             // true             // true             // true             // true             // true             // true             // false            // true
{}                  // Object           // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
{foo: 'bar'}        // Object           // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
new Object({})      // Object           // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
new class { }       //                  // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
new class Foo { }   // Foo              // object           // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
Number              // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
String              // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
Boolean             // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
Array               // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
Object              // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
class { }           // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
class Bar { }       // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
function() { }      // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false
() => { }           // Function         // function         // false            // false            // true             // false            // true             // false            // false            // false            // false            // false            // false            // false

Upvotes: 2

Cale McCollough
Cale McCollough

Reputation: 360

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;
  }
}

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22265

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.

Upvotes: 0

Himanshu Shekhar
Himanshu Shekhar

Reputation: 1262

XOR operation can be used to detect number or string. number ^ 0 will always give the same number as output and string ^ 0 will give 0 as output.

Example: 
   1)  2 ^ 0 = 2
   2)  '2' ^ 0  = 2
   3)  'Str' ^ 0 = 0

Upvotes: 3

Steve
Steve

Reputation: 4975

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

Upvotes: 0

Ermac
Ermac

Reputation: 1250

Beware that typeof NaN is... 'number'

typeof NaN === 'number'; // true

Upvotes: 9

MarredCheese
MarredCheese

Reputation: 20791

Simple and thorough:

function isNumber(x) {
  return parseFloat(x) == x
};

Test cases:

console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));

console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));

Upvotes: 15

adius
adius

Reputation: 14952

Since ES2015 the correct way to check if a variable holds a valid number is Number.isFinite(value)

Examples:

Number.isFinite(Infinity)   // false
Number.isFinite(NaN)        // false
Number.isFinite(-Infinity)  // false

Number.isFinite(0)          // true
Number.isFinite(2e64)       // true

Number.isFinite('0')        // false
Number.isFinite(null)       // false

Upvotes: 56

Amir Forsati
Amir Forsati

Reputation: 5960

Type checking

You can check the type of variable by using typeof operator:

typeof variable

Value checking

The code below returns true for numbers and false for anything else:

!isNaN(+variable);

Upvotes: 3

BitOfUniverse
BitOfUniverse

Reputation: 6021

Best way to do that is using isNaN + type casting:

Updated all-in method:

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

The same using regex:

function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

------------------------

isNumber('123'); // true  
isNumber('123abc'); // false  
isNumber(5); // true  
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber('   '); // false

Upvotes: 293

osomanden
osomanden

Reputation: 611

Or just use the invert of isNaN():

if(!isNaN(data))
  do something with the number
else
  it is a string

And yes, using jQuery's $.isNumeric() is more fun for the buck.

Upvotes: 9

KV Prajapati
KV Prajapati

Reputation: 94645

Try this,

<script>
var regInteger = /^-?\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>

Upvotes: 17

user663031
user663031

Reputation:

Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.

function is_number(x) { return x === x+0;  }
function is_string(x) { return x === x+""; }

For some unfathomable reason, x===x+0 seems to perform better than x===+x.

Are there any cases where this fails?

In the same vein:

function is_boolean(x) { return x === !!x; }

This appears to be mildly faster than either x===true || x===false or typeof x==="boolean" (and much faster than x===Boolean(x)).

Then there's also

function is_regexp(x)  { return x === RegExp(x); }

All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question. I cannot think of such an operation for dates.

For NaN, there is

function is_nan(x) { return x !== x;}

This is basically underscore's version, and as it stands is about four times faster than isNaN(), but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber. Why? What other objects would not equal themselves? Also, underscore uses x !== +x--but what difference could the + here make?

Then for the paranoid:

function is_undefined(x) { return x===[][0]; }

or this

function is_undefined(x) { return x===void(0); }

Upvotes: 10

Jakob Gade
Jakob Gade

Reputation: 12419

You're looking for isNaN():

console.log(!isNaN(123));
console.log(!isNaN(-1.23));
console.log(!isNaN(5-2));
console.log(!isNaN(0));
console.log(!isNaN("0"));
console.log(!isNaN("2"));
console.log(!isNaN("Hello"));
console.log(!isNaN("2005/12/12"));

See JavaScript isNaN() Function at MDN.

Upvotes: 48

Yoraco Gonzales
Yoraco Gonzales

Reputation: 737

What do you thing about this one?

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

Upvotes: 0

ZagNut
ZagNut

Reputation: 1451

uh, how about just:

function IsString(obj) {
    return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}

After further review many months later, this only guarantees obj is an object that has the method or property name toLowerCase defined. I am ashamed of my answer. Please see top-voted typeof one.

Upvotes: 7

Tanah
Tanah

Reputation: 459

typeof works very well for me in most case. You can try using an if statement

if(typeof x === 'string' || typeof x === 'number') {
    console.log("Your statement");
}

where x is any variable name of your choice

Upvotes: 3

Stephen Niedzielski
Stephen Niedzielski

Reputation: 2637

For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:

The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity . Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number. You may want to define your own isNumber function:

var isNumber = function isNumber(value) { return typeof value === 'number' &&
            isFinite(value);
};

Upvotes: 1

jemiloii
jemiloii

Reputation: 25719

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.

Upvotes: 0

Wil Moore III
Wil Moore III

Reputation: 7194

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)\]/);

Upvotes: 0

Angelos
Angelos

Reputation: 237

Jsut an FYI, if you're using jQuery you have

$.isNumeric() 

to handle this. More details on http://api.jquery.com/jQuery.isNumeric/

Upvotes: 4

hosein
hosein

Reputation: 519

function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}

Upvotes: 1

Roland
Roland

Reputation: 9701

I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.

So if you care about performance, I would, I'd use this:

typeof str === "string" || str instanceof String

for checking if the variable is a string (even if you use var str = new String("foo"), str instanceof String would return true).

As for checking if it's a number I would go for the native: isNaN; function.

Upvotes: 8

Jonathon
Jonathon

Reputation: 165

Simply use

myVar.constructor == String

or

myVar.constructor == Number

if you want to handle strings defined as objects or literals and saves you don't want to use a helper function.

Upvotes: 0

Bounasser Abdelwahab
Bounasser Abdelwahab

Reputation: 132

jQuery uses this:

function isNumber(obj) {
  return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}

Upvotes: 5

Sampson
Sampson

Reputation: 268344

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string
typeof 123;           // number

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

Upvotes: 505

Michael Mikowski
Michael Mikowski

Reputation: 1279

This solution resolves many of the issues raised here!

This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:

// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
  if (undefined === data ){ return 'Undefined'; }
  if (data === null ){ return 'Null'; }
  return {}.toString.call(data).slice(8, -1);
};  
// End public utility /getVarType/

Example of correctness

var str = new String();
console.warn( getVarType(str) ); // Reports "String"    
console.warn( typeof str );      // Reports "object"

var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num );      // Reports "object"

var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list );        // Reports "object"

Upvotes: 4

towry
towry

Reputation: 4286

@BitOfUniverse's answer is good, and I come up with a new way:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

I know 0 can't be dividend, but here the function works perfectly.

Upvotes: 3

pocesar
pocesar

Reputation: 7050

since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var). Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/ The important side of .test is that it WON'T throw an exception if the var isn't an string, the value can be anything.

var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;

regex.test(val)       // false 
val = '1234';
regex.test(val)       // true
val = '-213';
regex.test(val)       // true
val = '-213.2312';
regex.test(val)       // true
val = '+213.2312';
regex.test(val)       // true
val = 123;
regex.test(val)       // true
val = new Number(123);
regex.test(val)       // true
val = new String('123');
regex.test(val)       // true
val = '1234e';
regex.test(val)       // false 
val = {};
regex.test(val)       // false 
val = false;
regex.test(val)       // false 
regex.test(undefined) // false 
regex.test(null)      // false 
regex.test(window)    // false 
regex.test(document)  // false 

If you are looking for the real type, then typeof alone will do.

Upvotes: 3

mrrena
mrrena

Reputation: 149

//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

//basic usage
is('String', 'test'); // true
is('Array', true); // false

Or adapt it to return an unknown type:

function realTypeOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}

//usage
realTypeOf(999); // 'Number'

May 12, 2012 Update: Full example at Javascript: A Better typeof.

Upvotes: 14

Related Questions