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>
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 usfalsebecause[]is a "truthy" value that coerces totruewhen tested as a boolean, and so![]isfalse.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,
+[]is0because it coerces the empty array to a number, which takes it through being a string (""), and+""is0.Finally, that value is used on
"false":"false"[0]is"f".And so on, the rest of it is just variations on that theme. (
!+[]istrue, which matters later.)