Back to Blog

JS Puzzle #shorts #quiz

Sandy LaneSandy Lane

Video: JS Puzzle #shorts #quiz by Taught by Celeste AI - AI Coding Coach

Watch full page →

JS Puzzle: [] + {} vs {} + []

In JavaScript, adding arrays and objects can produce surprising results due to type coercion and how the plus operator works with different types. This puzzle explores the difference between [] + {} and {} + [], revealing how JavaScript interprets these expressions differently.

Code

console.log([] + {});  // Output: "[object Object]"
// Explanation: [] is converted to an empty string "", {} is converted to "[object Object]"
// So "" + "[object Object]" results in the string "[object Object]"

console.log({} + []);  // Output: 0
// Explanation: When {} is at the start of a line, JavaScript interprets it as a block, not an object literal
// So this is treated as an empty block followed by +[], which is unary plus applied to []
// [] converts to 0, so the result is 0

// To force {} to be an object literal, wrap in parentheses:
console.log({} + []);          // 0
console.log(({}) + []);        // "[object Object]"
// Now {} is an object, converted to "[object Object]", [] to "", concatenated as "[object Object]"

Key Points

  • The plus operator (+) concatenates strings or adds numbers, depending on operand types.
  • Empty arrays convert to empty strings when used with +, while objects convert to "[object Object]".
  • JavaScript interprets a standalone {} at the start of a line as a block, not an object literal.
  • Using parentheses forces {} to be treated as an object literal, changing the result.
  • Understanding JavaScript's type coercion and parsing rules is key to predicting these outcomes.