Date silently accepts anything

sept 6 , 2011

    d = new Date("couldn't you please throw an exception here instead?");

    // No! You get the joy of discovering this error somewhere unrelated,
    // much later; at the point of use, in an innocent part of your code:

    d.getTime(); // => NaN

johan || @ecmanaut


iteration demoralization

july 2 , 2011

See if you can guess what this will output:


    function allNames() {
      var names = [ 'dan', 'anthony', 'pavel' ];
      for (name in names) {
        console.log(name);
      }
    }

    allNames();

If you guessed this:

0
1
2

...then you are right! Congratulations!

What you might not have guessed, is what this will output:


    console.log(window.name);

it's:

"2"

Iteration is assignment, and without the use of the var keyword, you're really using the global object - which in this context is the window object.

So the original function is equivalent to:


    function allNames() {
      var names = [ 'dan', 'anthony', 'pavel' ];
      for (window.name in names) {
        console.log(name);
      }
    }

By @danlash


min less max

june 1 , 2011

This beauty is courtesy of TiTi ...lets look at some code.



    Math.max();
    // -Infinity

    Math.min();
    // Infinity

Ok, so, there is a good reason for this behaviour. It might even make sense if you happen to occasionally omit args from your min/max calls. ;)

You see, the min/max implementations need something to compare to and Infinity and -Infinity are the only safe values to use for that comparison. @kriskowell goes into more better detail here and was quickly followed by @brendaneich whom not only wrote js in 10 days but can rock out unicode Infinity symbols without looking them up ...I shit you not.

Of course, due to this behaviour js allows for this code humour:

Math.min() < Math.max();
// false

Oh JavaScript, I still love you.


parseInt is not eval

may 4 , 2011

Remember folks, parseInt() is not eval().


  parseInt("1", 10); // 1
  eval("1") // 1

Pretty much the same thing....wait.


  parseInt("1 + 1", 10); // 1
  eval("1 + 1") // 2

In the first example the first digit is recognized and the rest of the string is thrown away. How intuitive. eval() at least gets it right.


  parseInt("1 - 1", 10); // 1
  eval("1 - 1") // 0

The string example takes the first digit and just throws out the rest of the string. And again, eval() with the correct solution.


  parseInt("1" + "1", 10) // 11
  eval("1" + "1") // 11

This time they both get the wrong answer, because the strings are concatenated before the numbers are evaluated.


  parseInt("1" - "1", 10); // 0
  eval ("1" - "1") // 0

Both right answers, because the subtraction symbol forces the strings into numbers before they get used.

-- @xjamundx


Fork me on GitHub