Fun parsing of one expression with square brackets

    Why in JavaScript:


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

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

    And here is no:

    > [[]+[]]-[]+[[]-[]]

    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"-1

    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.

    > [""]-[]

    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:

    > [[]-[]]

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

    > 0+[0]

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

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

    > 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"-[]

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

    > 1+[[]-[]]

    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"-1

    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: and then use it to bypass regular expression filtering in eBay:

    Also popular now: