typeof number is not number

Jul 15, 2010

How do you determine if a number is an integer in JavaScript?


    x
= 1;
   
    x
=== Math.floor(x);
   
// returns true

But what happens if we try to add a method for this to the Number prototype?


   
Number.prototype.isInteger = function() {
     
return this === Math.floor(this);
   
}
   
    x
= 1;
   
    x
.isInteger();
   
// returns false!

Why? It turns out that when you add methods to Number, the type of the number inside the method becomes "object" rather than "number", but Math.floor returns a result of type "number". If you use the === operator, the two values are no longer equal because they're different types. So the method can be fixed two ways.

Solution 1 is to avoid comparing types:


   
Number.prototype.isInteger = function() {
     
return this == Math.floor(this);
     
// works but breaks if you care about 0 vs other falsy values
   
}

Solution 2 is better; cast "this" to the Number type and then the types are equal.


   
Number.prototype.isInteger = function() {
     
return Number(this) === Math.floor(this);
   
}

--- @attaboy


fail

Jul 12, 2010

Let's take the last post a step further:


    console
.log( (![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]] ) // "fail"

Breaking that mass of symbols into pieces we notices, that the following patten occurs often:


    console
.log( (![]+[]) ) // "false"
    console
.log( ![] ) // false

So we try adding [] to false. But through a number of internal function calls( binary + Operator -> ToPrimitive -> [[DefaultValue]]) we end up with converting the right operand to a String:


    console
.log( [].toString() ) // ""
    console
.log( (![]+[].toString()) ) // false + ""

Aha, so we are concatenating strings here! Now this is plain obvious! Moving on to the next bit:


    console
.log( [+[]] ) // [ 0]
    console
.log( +[] ) // 0

Thinking of a String as an Array we can access its first character via [0]. So "false"[0] returns "f".

I think you got the idea now and can figure out the rest by yourself!

Thanks to Mathias Bynens for pushing this out int the web.


length of what now

Jul 11, 2010

This made me laugh. Out loud even!


    console
.log((!+[]+[]+![]).length);
   
// 9

Huh, wtf?! Lets see what we're getting the length of...


    console
.log((!+[]+[]+![]));
   
// "truefalse"

Ah! lulz. thanks to @stepiiik and @DavidGrudl!


Fork me on GitHub