1

How can []+(-~{}-~{}-~{}-~{})+(-~{}-~{}) be equals to "42" in javascript?

Sorry for the title, but it can make it easier for other people to find the post. (I saw it mentioned in a forum)

Solved :
[] will convert the expression to a String.
-~{} = -1
So
-~{}-~{}-~{}-~{} = 4
-~{}-~{} = 2

The rest is String concatenation

gr3g
  • 2,866
  • 5
  • 28
  • 52
  • 2
    Without going through all the math, the basics is that javascript does some [weird stuff](http://wtfjs.com/) when you try to add/subtract different types together. – william.taylor.09 Feb 05 '16 at 21:06
  • 2
    Yeah, this coupled with `~{} -> -1` will explain the given expression. – Jared Goguen Feb 05 '16 at 21:08
  • It just has to do with empty arrays and empty objects equaling some numbers when you flip the bits and start adding them together – Nick Zuber Feb 05 '16 at 21:08
  • Does `valueOf()` and `toString()` makes to difference? Maybe something easier to begin with : `[] + {}` = [Object Object] `{} + []` = 0 – gr3g Feb 05 '16 at 21:08
  • 3
    Note that in the end it's doing `[] + 4 + 2`. `[] + 4` is `"4"` so then + becomes concatenation, i.e. `"4" + 2` = `"42"` – Nebula Feb 05 '16 at 21:08
  • This is different question, the other one does not contain ~{}! This is question about similar feature, but it is different. Especially search for ~{} would find this one, but not the other – Hurda Feb 05 '16 at 21:18
  • I've understood the question I posted in the comment. But still, If someone could provide a step by step explanation for this one... – gr3g Feb 05 '16 at 21:22

0 Answers0