js puzzle

April 09, 2016

I came across a tweet that had this bit of puzzling sample code:

js puzzle

Most of this made sense to me, except for the part of the properties being assigned and then either accessible or being undefined. I had a hunch that it was related to something I blogged about previously.

Turns out when using the .call it’s actually returning an object. That first line is the equivalent of var five = new Number(5); . This means:

var five = new Number(5); five instanceof Number; // true typeof five; // 'object'

While it’s an object, you can add your properties but as soon as it’s autoboxed/primitive wrapped by the ++ , it loses it’s abilities to hold those properties. This is shown by the fact that the instanceof and typeof values are now different:

// ... continuing from previous example five++; // is now 6 five instanceof Number; // false typeof five; // 'number'

The rest of the puzzle is playing with the timing of return values and the difference of an assignment from number++ and ++number.

At least that’s the way I understand it, let me know if I’ve missed anything.