1

When I console the below expressions I get the following results. Can anyone explain what is internally going on in javascript? Why adding an empty array with integer results to string?

console.log([] + 50); // "50"
console.log([] - 50); // -50

console.log({} + 50); // "[object Object]50"
console.log({} - 50); // NaN
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
HarryKant
  • 55
  • 7
  • Hey, I saved your edits and didn't roll back. There might be some mistake :) – HarryKant Apr 08 '19 at 13:08
  • You must have rolled it back accidentally (since [you did do a rollback](https://stackoverflow.com/revisions/55574003/3)). No biggie. :-) – T.J. Crowder Apr 08 '19 at 13:09
  • The answers to the linked question cover this, but: Fundamentally: Both of those binary operators (`+` and `-`) coerce their operands, but they do it differently: `+` converts both of its operands to primitives based on their own preferred kind of primitive (it doesn't ask for a specific kind), and then if either of the operands is a string, it does string concatenation; otherwise, it converts both to numbers and does addition. So `[] + 50` becomes `"" + 50` because when you coerce an array to a primitive, it does a `join("")`, and `[].join("")` is `""`. `"" + 50` is `"50"`. *(cont'd)* – T.J. Crowder Apr 08 '19 at 13:16
  • *(continuing)* But `-` always converts to number. If the standard primitive for the operand isn't a number (it's a string or boolean, etc.), `-` converts that primitive to a number. `[] - 50` becomes `"" - 50` initially because, again, arrays convert to string via `join`. `"" - 50` becomes `0 - 50` because `""` is converted to the number `0`. When you convert `{}` to a string, you get the string `"[object Object]"`. So `{} + 50` is `"[object Object]" + 50` which is `"[object Object]50`. *(cont'd)* – T.J. Crowder Apr 08 '19 at 13:17
  • *(continuing)* `{} - 50` is `"[object Object]" - 50` which is `NaN - 50` which is `NaN` because any math operation using `NaN` results in `NaN`. – T.J. Crowder Apr 08 '19 at 13:17
  • thanks, @T.J.Crowder :) great help !! – HarryKant Apr 09 '19 at 10:27

0 Answers0