What is the importance of Symbol.isConcatSpreadable in JavaScript?


Symbol.isConcatSpreadable

This well-known symbol is used to configure if an object should be flattened to its array elements when using the Array.prototype.concat() method. If it is false then there is no flattening of the array takes place. By default, the Symbol.IsConcatSpreadable is true. Therefore until and unless it is not declared explicitly flattening of the array can't be avoided.

Without Symbol

Example

In the following example, the symbol Symbol.IsConcatSpreadable was doesn't stated explicitly. So by default, the array was flattened as shown in the output.

<html>
<body>
<script>
   var arr1 = ['mango', 'apple', 'guava'];
   var arr2 = ['cashew', 'pista', 'bhadham'];
   var res1 = arr1.concat(arr2);
   console.log(res1);
</script>
</body>
</html>

Output

["mango", "apple", "guava", "cashew", "pista", "bhadham"]


With Symbol

Example

In the following example, the symbol Symbol.IsConcatSpreadable is stated explicitly so the flattening of array didn't take place as shown ion the output.

<html>
<body>
<script>
   var arr1 = ['mango', 'apple', 'guava'];
   var arr2 = ['cashew', 'pista', 'bhadham'];
   arr2[Symbol.isConcatSpreadable] = false;
   var res2 = arr1.concat(arr2);
   console.log(res2);
</script>
</body>
</html>

Output

["mango", "apple", "guava", Array(3)]

Updated on: 31-Jul-2019

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements