A recent tweet contained this snippet of JavaScript.
Can someone please explain what is happening in it step by step?
> function dis() { return th
There are two different ways to represent a number:
var a = 5;
var b = new Number(5);
The first is a primitive, the second an object. For all intents and purposes both behave the same, except they look different when printed to the console. One important difference is that, as an object, new Number(5) accepts new properties just like any plain {}, while the primitive 5 does not:
a.foo = 'bar'; // doesn't stick
b.foo = 'bar'; // sticks
As for the initial dis.call(5) part, please see How does the "this" keyword work?. Let's just say that the first argument to call is used as the value of this, and that this operation forces the number into the more complex Number object form.* Later on ++ forces it back into the primitive form, because the addition operation + results in a new primitive.
> five = dis.call(5) // for all intents and purposes same as new Number(5)
Number {[[PrimitiveValue]]: 5}
> five.wtf = 'potato'
"potato"
> five.wtf
"potato"
A Number object accepts new properties.
> five++
++ results in a new primitive 6 value...
> five.wtf
undefined
> five.wtf = 'potato?'
"potato?"
> five.wtf
undefined
...which does not have and does not accept custom attributes.
* Note that in strict mode the this argument would be treated differently and would not be converted to a Number. See http://es5.github.io/#x10.4.3 for the implementation details.