parseint radix

feb 22 , 2013
    parseInt('fuck');     // NaN
    parseInt('fuck', 16); // 15

So remember kids, always supply a radix!

@kevincennis


why am i a number

feb 21 , 2013

Can someone tell me?

    "Why am I a " + typeof + ""; // "Why am I a number"

@jhnnns


I think I can tell you.

typeof requires some value or expression that is evaluated and passed then to typeof as an argument. +"" is treated as expression because + operator can be used as an unary operator (syntax is: + UnaryExpression). + converts its operand to Number type. So, + "" is evaluated to 0 and then 0 is passed to typeof.

Note that we can cast strings to numbers by preceding them with +:


(2 + "3");  // 23
(2 + +"3"); // 5
(+"");      // 0

@wojciechfornal


unicode vars

feb 13 , 2013

ECMAScript allows you to use unicode variable names, just use the usual \uXXXX codes:

    var \u1000 = {
      \u1001: 'foo',
      \u1011: 'bar'
    };

    console.log( \u1000.\u1001 ); // prints 'foo'
    console.log( \u1000.\u1011 ); // prints 'bar'

WTF right?

By @manekinekko


obfuscated fibonacci

feb 12 , 2013
  var fib = function (_) {
      for(_=[+[],++[[]][+[]],+[],_],_[++[++[++[[]][+[]]][+[]]][+[]]]=(((_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]]))&(((--[[]][+[]])>>>(++[[]][+[]]))))===(_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])))?(_[++[++[[]][+[]]][+[]]]=++[[]][+[]],_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])):+[];_[++[++[++[[]][+[]]][+[]]][+[]]]--;_[+[]]=(_[++[[]][+[]]]=_[++[++[[]][+[]]][+[]]]=_[+[]]+_[++[[]][+[]]])-_[+[]]);
      return _[++[++[[]][+[]]][+[]]];
  }

  console.assert(fib(-1) === 0);
  console.assert(fib(0) === 0);
  console.assert(fib(1) === 1);
  console.assert(fib(2) === 1);
  console.assert(fib(3) === 2);
  console.assert(fib(4) === 3);
  console.assert(fib(5) === 5);
  console.assert(fib(6) === 8);
  console.assert(fib(7) === 13);
  console.assert(fib(32) === 2178309);
  console.assert(fib(46) === 1836311903);
  console.assert(fib(47) === 2971215073);
  console.assert(fib(63) === 6557470319842);

  console.log('done!');

I've combined (for fun) a few WTFs to make something bigger.

Just in case... don't code in JS like that. Seriously.

-- @s3a


magic function properties

feb 5 , 2013
    var f = function() { };
    f.foo = 'foo'; // sets f.foo to 'foo'

Functions are objects, so you can set properties on them after creation.

    f.name; // is ''
    f.name = 'foo';
    f.name; // is still ''

But not all the time.

    var f = function myFunction() { };
    f.name; // is 'myFunction'

Functions happen to have magic properties. One of them is the non-standard .name, which stores the function's first name and read-only.

@tmcw


Fork me on GitHub