When using JavaScript, the addition operator (+) serves to add the value of one numeric expression to another or concatenate two strings.
The behavior of the + operator is determined by the types of the two expressions involved.
If both expressions are numeric or Boolean, they will be added together.
1 + 1;
// 2
true + false;
// 1
true + true;
// 2
When both expressions are strings, they will be concatenated:
"hel" + "lo";
// "hello"
If one expression is numeric and the other is a string, they will also be concatenated:
1 + {}
// "1[object Object]"
In this case, [object Object]
is the string representation of {}
:
String({})
// "[object Object]"
However, things take an unexpected turn if the first operand of +
is an empty object literal. JavaScript sees this as an empty code block and disregards it.
Therefore, {} + 1
is simply seen as +1
, resulting in a value of 1.
But why is the initial {}
interpreted as a code block? This is because when parsed as a statement, curly braces at the start are viewed as indicating the beginning of a code block.
To address this issue, you can manipulate the input to be evaluated as an expression, providing the expected outcome:
({} + 1)
// "[object Object]1"
For further insights on this topic, you may find this informative post helpful.