JavaScript type coercion with strings and indexing

268 views Asked by At

In the below snippet why does whatDoesItDo() function return "fail" as string? It would be helpful if someone can explain the concept behind such behavior.

function whatDoesItDo() {

  return (![] + [])[+[]] + (![] + [])[+!+[]] +
    ([![]] + [][
      []
    ])[+!+[] + [+[]]] + (![] + [])[!+[] + !+[]];

}

function result() {

  document.getElementById("result").innerHTML = whatDoesItDo();

}

result();
<html>

<body>
  <p id="result"></p>
</body>

</html>

1

There are 1 answers

8
T.J. Crowder On BEST ANSWER

You're seeing the effects of A) Type coercion, B) Indexing into strings using [], and C) String concatenation.

Let's look at the first bit:

(![] + [])[+[]]

![] gives us false because [] is a "truthy" value that coerces to true when tested as a boolean, and so ![] is false.

Then we add [] to it, which turns them both into strings because the + operator coerces both its arguments to strings if either of them isn't a number (if both are numbers, it adds), giving us "false" (because [].toString() is [].join() which is "").

So now we have "false".

Then, +[] is 0 because it coerces the empty array to a number, which takes it through being a string (""), and +"" is 0.

Finally, that value is used on "false": "false"[0] is "f".

And so on, the rest of it is just variations on that theme. (!+[] is true, which matters later.)