Timeline for type checking in javascript
Current License: CC BY-SA 2.5
11 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Nov 12, 2020 at 3:01 | comment | added | user1948585 | A functional way of type checking stackoverflow.com/a/64794158/1948585 | |
| Nov 22, 2015 at 23:20 | comment | added | RobG | This answer should be updated as it's inconsistent with the ECMAScript 2015 Number.isInteger function. It should return false for Infinity, not true. | |
| Feb 17, 2014 at 15:04 | comment | added | yhpark |
Beware, typeof new Number(foo) is "object"
|
|
| Jan 24, 2014 at 4:26 | comment | added | Mike Stay | You can also check if a number x is a valid array index, i.e. a 32-bit integer with x === (x|0). The binary operator casts to a 32-bit int internally, so if casting to an int and then back to a double leaves the value the same, it's a valid 32-bit int. Anything out of range or the wrong type gets cast to 0. | |
| Nov 2, 2013 at 6:09 | comment | added | jrista |
One could also use constructor equivalence: foo.constructor === Number. One could then throw in the Math.floor or parseInt check to verify the Number is actually an int. The benefit of this is you are actually checking a concrete type name, rather than a string, however that may not quite carry the weight it does in a strongly typed language.
|
|
| Jul 9, 2013 at 21:44 | comment | added | Andrei | If you're using jQuery, you can use it's $.type() function. Ex. $.type("1") # => "string" | |
| Oct 7, 2012 at 10:09 | comment | added | Quentin | @NullUserException — That's what I said. | |
| Oct 7, 2012 at 6:54 | comment | added | NullUserException | "it doesn't distinguish between different types of Number" That's because there are no different types of Number. All numeric values in JS are 64-bit floats. | |
| Dec 22, 2010 at 23:41 | vote | accept | sova | ||
| Dec 22, 2010 at 23:29 | comment | added | m4tt1mus | you can also use isNaN(foo) w3schools.com/jsref/jsref_NaN.asp instead of typeof | |
| Dec 22, 2010 at 23:21 | history | answered | Quentin | CC BY-SA 2.5 |