JavaScript traps · JavaScript

JavaScript: [1,2,3] + [4] = "1,2,34"?!PRO

+ turns both arrays into text and glues them. Spread or concat makes a real array.

// [1,2,3] + [4] = "1,2,34" ?!
// + doesn't join arrays: it turns both into TEXT ("1,2,3" and "4") and glues them.
console.log([1, 2, 3] + [4]);      // 1,2,34 ?!
console.log(typeof ([1] + [2]));   // string

// Fix: spread (or concat) to make a new array
console.log([...[1, 2, 3], 4]);    // [1, 2, 3, 4] ✓
console.log([1, 2, 3].concat([4]));  // [1, 2, 3, 4] ✓
Open code JS10 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code JS10 in Code Library.