Skip to content

Instantly share code, notes, and snippets.

@zacechola
Created May 12, 2015 20:30
Show Gist options
  • Save zacechola/60ba5e4374520d2d97d1 to your computer and use it in GitHub Desktop.
Save zacechola/60ba5e4374520d2d97d1 to your computer and use it in GitHub Desktop.
JavaScript is logical
[1] + [6] * [2] == 112 // true

Because:

[6] * [2] coerces to "6" * "2", which further coerces to 6 * 2, which equals 12.

[1] + 12 coerces to "1" + 12, which changes the meaning of "+" to concatenate, so the string "1" is concatenated to number 12, resulting in the string "112".

"112" == 112 makes a whole lot of sense now, doesn't it?

@zacechola
Copy link
Author

I should note here that the reason [6] * [2] evaluates first is because of operator precedent.

As you know, 1 + 6 * 2 is equal to 13 and not 14, because multiplication is evaluated before addition.

Presumably, most people who complain about implicit coercion in JavaScript would prefer left-to-right evaluation, because math is hard. Or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment