The random rantings of a concerned programmer.

Jul 17

Fun Javascript Primitives Time

Category: Random

Suppose you have some javascript, and you’re inspecting some arguments passed in from another developer because you’re an asshole and want to throw TypeError‘s whenever possible to spite the fact that you’re not using a strong, statically-typed language. So you write some code:

function dongstrap(a1) {
  if (!(a1 instanceof String)) {
    throw new TypeError("ASSHATS");
  }
}

You go to test it and … wait, what? dongstrap("dongs"); doesn’t throw? So you fire up your handy javascript REPL and, sure enough, "" instanceof String == false.

What. The. Fuck.

Okay, so string literals aren’t really objects. Okay. So they shouldn’t behave like objects.

String.prototype.dongs = function() { 
  throw new Error("dongs"); 
}

"".dongs(); // Throws "dongs"

Okay, so string literals BEHAVE like objects, but are not objects. I imagine that they were originally vanilla primitive types — you couldn’t coerce them to ever act like objects and had to check the type via typeof whatever === 'string'. Fine, I get it, Javascript is old as shit. And then someone else comes along and is like

SMALLTALK IS LOVE, SEX ME SOME RUBY, ALL VALUES ARE CAN BE OBJECTS

And that’s fine and all; but during the actual implementation meeting (probably for backwards-compatibility nonsense), they were like “HEY, LET’S TACK THIS SHIT ON TOP OF IT AND MAKE ALL KINDS OF HOLES FOR PEOPLE TO FALL INTO, JOB SECURITY ETC” and there were nods all around, because it was just after the first dot-com bubble and everyone was sleepless at night with worry about how they’d make their next mortgage payment, much less send their still-infantile children through an over-priced, over-valued 4-year course on increasing bodily tolerance to liquor.

So if we revisit the original function, and instead invoke the String constructor directly –

dongstrap(new String("dongs"));

The exception gets thrown as expected.

And that would make sense and all, but we’ve already rewritten to

function dongstrap2(a1) {
  if (typeof a1 === 'string') {
    throw new TypeError('seriously');
  }
}

…and guess what typeof(new String('')) is? Yeah. It’s not string. It’s object. So, frustrated and infuriated, you replace the keys displaced from slamming your keyboard on the ground and with gritted teeth smash out the third and final implementation before breaking out the fifth of whiskey stashed in your desk drawer next to the loaded colt .45

function dongstrap3(a1) {
  if (!(a1 instanceof String) && !(typeof a1 === 'string')) {
    throw new TypeError('fuck you');
  }
}

After commiting your changes, as you raise the revolved to your jaw, you have two thoughts:

  1. Why the fuck was I, nay, anyone, writing in such a braindead language?
  2. This madness probably applies to Numbers as well.

Tagged with: i give up, , whiskey
4 comments