• JavaScript Video Tutorials

JavaScript - Symbol.isConcatSpreadable Property



The Symbol.isConcatSpreadable property is used to customize the behavior of an object when it is passed as an argument to the Array.prototype.concat() method. If we tried to call concat() on array, it automatically flattens nested arrays. However, if we tried to pass an object instead of an array to concat(), it will be treated as a single object and not flatten. This can cause an issue if you want to concatenate arrays in a way that flatten arrays within objects.

This is when the use of Symbol.isConcatSpreadable is necessary. When an object's symbol property is set to true, it means that concat() should flatten the object when it is supplied to it. The object is handled as a single item and is not flattened if it is set to false or not present.

Syntax

Following is the syntax of JavaScript Symbol.isConcatSpreadable property −

Array[Symbol.isConcatSpreadable]

Parameters

This property doesn't accept any kind of parameters.

Return value

This property returns the Concatenation Result.

Examples

Example 1

Let's look at the following example, where we are going to use the isConcatSpreadle with a Array set to false.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         Symbol.prototype.lengthx = function() {
            return this.description.length;
         };
         const a = Symbol('TutorialsPoint');
         document.write(a.lengthx());
      </script>
   </body>
</html>

If we execute the above program, it will displays the number on the webpage.

Example 2

Consider the another scenario, where we are going to use the isConcatSpreadable with a Array set to true.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = ['a', 'b', 'c'];
         const y = [1, 4, 3];
         y[Symbol.isConcatSpreadable] = true;
         const result = x.concat(y);
         document.write(JSON.stringify(result));
      </script>
   </body>
</html>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to use the isConcatSpreadable with Array.from() method.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            length: 3,
            0: 'Rabbit',
            1: 'Fox',
            2: 'Lion',
            [Symbol.isConcatSpreadable]: true
         };
         const a = ['Carrot'];
         const result = Array.from(a).concat(x);
         document.write(JSON.stringify(result));
      </script>
   </body>
</html>

When we execute the script, it will displays a text on the webpage.

Advertisements