Symbol.isConcatSpreadable for Array Concatenation
You'll learn how to control whether array-like objects spread out their elements during concat() operations using Symbol.isConcatSpreadable.
What Is Symbol.isConcatSpreadable?
When you use the concat() method to join arrays, JavaScript normally spreads out the elements of array arguments. But what about array-like objects? Symbol.isConcatSpreadable is a well-known symbol that lets you control this spreading behavior explicitly.
By setting this property to true or false on an object, you tell concat() whether to treat the object as a collection to be spread (unpacked) or as a single item to be added whole.
How It Works
For regular arrays, concat() spreads elements by default. But you can override this:
const arr1 = [1, 2];
const arr2 = [3, 4];
// Normal behavior - elements spread
console.log(arr1.concat(arr2)); // [1, 2, 3, 4]
// Disable spreading
arr2[Symbol.isConcatSpreadable] = false;
console.log(arr1.concat(arr2)); // [1, 2, [3, 4]]
For array-like objects (objects with a length property and indexed elements), you can enable spreading:
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
// Without the symbol - added as single object
console.log([].concat(arrayLike)); // [{ 0: 'a', 1: 'b', length: 2 }]
// Enable spreading
arrayLike[Symbol.isConcatSpreadable] = true;
console.log([].concat(arrayLike)); // ['a', 'b']
Think of it like packing instructions: the symbol tells concat() whether to "unpack the box" (spread elements) or "keep the box intact" (add as-is).
Key Takeaway: Symbol.isConcatSpreadable controls whether objects spread their elements during concat() — set it to true to enable spreading for array-like objects, or false to prevent spreading for arrays.