Hiprup

What is the output of [] + [] and [] + {}?

These show how the + operator coerces objects to strings.

  • [] + [] — both arrays become empty strings, so the result is "" (an empty string).

  • [] + {} — the array becomes "" and the object becomes "[object Object]", giving "[object Object]".

Why: + with a non-number triggers string conversion, and arrays/objects convert through their default toString.

console.log([] + []);     // '' (empty string)
console.log([] + {});     // '[object Object]'
console.log({} + []);     // '[object Object]' (in console/expression)
// {} + [] at line start = 0 (block + unary plus)

// How it works:
console.log([].toString());    // '' (empty string)
console.log({}.toString());    // '[object Object]'
console.log([1,2].toString()); // '1,2'

// More coercion fun
console.log([] == false);      // true ([] -> '' -> 0 == 0)
console.log([] == ![]);        // true! ([] -> 0, ![] -> false -> 0)
console.log(null + 1);         // 1 (null -> 0)
console.log(undefined + 1);    // NaN (undefined -> NaN)
console.log('5' + 3);          // '53' (string concatenation)
console.log('5' - 3);          // 2 (string coerced to number)

Arrays and objects are converted to strings by the + operator when used with non-numbers. [].toString() = '' and {}.toString() = '[object Object]'. String + String = concatenation.

The {} + [] ambiguity depends on whether {} is parsed as a block or object literal. These demonstrate why explicit type conversion and === are essential.

Know the toString outputs: [] = '', {} = '[object Object]', [1,2] = '1,2'. The + operator triggers string conversion when either operand is a string-like. [] == ![] = true is the most mind-bending example.

These questions test coercion knowledge — explain the step-by-step conversion.

What is the output of [] + [] and [] + {}? | Hiprup