eval changes
eval() is a mysterious function. More so than people believe, hell its spec isn't even clear. And so i present... The two stages of eval denial.
Try out these functions with
[foo("foo=2"),foo]
and take that path with me.
Tested on chrome, firefox ,opera, and safari.
Apparently eval is evil.
Doesn't seem so evil.
function foo(x){var foo=1;eval(x);return foo;};
//[2,function foo(x){var foo=1;eval(x);return foo;}]
Apparently assigning eval to a variable changes how it acts. WTF.
...Ok I can deal with that I guess.
function foo(x){var foo=1, bar=eval;bar(x);return foo;};
//and just returning it, not saving it
function foo(x){var foo=1;(function(){return eval})(x);return foo;};
//[1, 2]
im not a number really
You've probably seen this one here before. NaN (Not a Number) suffers from a terrible case of self-deception.
typeof NaN
//=> number
--- @3rdEden
Its still hilarious. Now, check this out:
3..toString();
// "3"
(By way of the wtfjs twitter firehouse. Cheers: @devongovett, @getify, @mahemoff. @cramforce, @mathias!)
magic increasing number
Look at me, I'm the magic increasing number!
9999999999999999
//=> 10000000000000000
--- @thomasfuchs
typeof number is not number
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