by

Weird JavaScript: How to make enemies with type coercion

Reading Time: 2 minutes

Who cares about friends? How would you like to piss of Todd who won’t shut up about this season’s IPAs and Elon Musk’s 4D chess he’s playing on Twitter? Screw Todd. No one likes him and he deserves to hurt for making you think about NFTs again.

Let’s use JavaScript’s type coercion in awful ways to make wonderful enemies.

A Salvador Dali style painting of a digital clock where it looks like an analog clock forgot numbers and grew weird assymetrical antennae as legs
I asked DALL-E for a Salvador Dali painting of a digital clock and it gave me this abomination.

Plus Array Just Because

Arrays coerce to strings, right? Right !?

const zero = +[]; // 0

Sad Boolean Plus Happy Boolean Make 1

const one = false + true; // 1

Welcome to otherwise again. This time the booleans are coerced to numbers, because thems the rules. So false becomes 0 and true becomes 1 and you become a light drinker.

Two Happy Booleans Make 2

If you understood the previous one, this one makes sense.

const one = true + true; // 2

Because true becomes 1 and 1 + 1 makes 2.

Bang Zero Hat Ate Nine

const nine = !0^8; // 9
  • !0 means not zero ,
    • so 0 is coerced to a boolean which is false
    • except it’s not false, so it’s true
    • And true is 1
  • The ^ is an XOR operator
    • it takes the numbers on the left and right and turns them into binary
    • And then it makes a new number where there’s 1’s only in the spots where both numbers didn’t have 1s
  • And yeah
    • When you 1^8 you get 9

Shutup, Nerd

(!null + !undefined)**(true^2) +['0'] +['0'] + (9^1) + [false + true] + [3][false*0] + ~-6;

/* 8008135 */
  • !null is true
    • and true is 1
  • !undefined is true
    • and true is 1
  • And 1 + 1 is 2
  • true^2 is 3
  • ['0'] + ['0'] is ’00’
  • 9^1 is XORed into 8
  • and we all know that false + true makes 1
  • and [3][false*0] is just a really oblique way of saying [3][0*0]
    • which is an overly convoluted way of saying [3][0]
    • Which is just a terrible path to 3
  • and then ~-6 is
    • using the ol’ bitflipper ~ to invert a -6‘s bits and make a 5
  • And when you add 8 + '00' + 8 + 1 + 3 + 5 you get a stringified number that looks a lot like ‘BOOBIES’ because when you use + with a string you always get a string.

You’re welcome.

1 Comment

Leave a Reply

You don't have to register to leave a comment. And your email address won't be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.