Fun parsing of one expression with square brackets

    Why in JavaScript:

    >1+[[]+[]]-[]+[[]-[]]-19

    In general, it is difficult at first glance to understand why this is so.

    What do you think [[]+[]]-[]+[[]-[]]==9?

    And here is no:

    > [[]+[]]-[]+[[]-[]]
     "00"

    But we know that when adding to a line in JS, concatenation occurs, and it would seem then the first expression should be 99:

    > 1+"00"-199

    How so?

    We'll have to disassemble from the beginning, first about two zeros:

    > []+[]
     ""

    It is clear here that empty arrays turned into empty lines and, when folded, generated an empty line.

    > [""]-[]
     0

    It’s also clear here, if you figure out that the second empty array is zero in terms of arithmetic, and the empty string (which the first array is reduced to for arithmetic) is also zero. Zero minus zero, while it makes sense. The second part also immediately becomes clear:

    > [[]-[]]
     [0]

    So we have a regular zero, and zero in the array, adding them, they are reduced to lines and concatenated:

    > 0+[0]
     "00"

    With double zero, everything is clear. Where did 9 come from?

    Read the addition, as expected, from left to right:

    > 1+[[]+[]]
     "1"

    We already figured out a lot of square brackets, an array with an empty string was reduced to an empty string and turned the whole unit into a unit-string ...

    > "1"-[]
     1

    ... and then subtracting zero turned it back into an integer.

    > 1+[[]-[]]
     "10"

    The set of square brackets on the right is ["0"], which turns into a string representation of the array, and is appended to the unit, which again turned into a string for this.
    And the final chord is quite obvious:

    > "10"-19

    And after all, everything seems to be correct ...

    In general, people make a full language on the Javascript interpreter using only brackets, an exclamation mark and plus: http://www.jsfuck.com/ and then use it to bypass regular expression filtering in eBay: http://thedailywtf.com/articles/bidding-on-security

    Also popular now: