Skip to content
Related Articles

Related Articles

JavaScript Symbol.species Property
  • Last Updated : 04 Mar, 2021

The Symbol.species property specifies a function-valued property that the constructor function uses to create derived objects. With this, we can create a derived object.

Syntax:

[Symbol.species]

Atrribute: The species accessor property can be used to allow subclasses to override the default constructor for objects.

Below examples illustrate the Symbol.species property in JavaScript.

Example 1:



Javascript




<script>
  
  // Created geek class that is extended by Array
  class geek extends Array {
    static get [Symbol.species]() {
      return Array;
    }
  }
  
  // Values assigned to geek
  const a = new geek(1, 2, 3, 4);
  //mapped values to geek object
  const mapped = a.map((x) => 2);
  
  console.log(mapped instanceof geek);
  //  output: false
  
  console.log(mapped instanceof geek);
  // output: false
</script>

Output:

false
false

Example 2:

Javascript




<script>
  class geek extends Array {
  
    // Overwrite species to the parent Array constructor
    static get [Symbol.species]() {
      return Array;
    }
  }
  let a = new geek(1, 2, 3, 5, 7, 8);
  let mapped = a.map((x) => x);
  
  console.log(mapped instanceof geek); // false
  console.log(mapped instanceof Array); // true
</script>

Output:

false
true
My Personal Notes arrow_drop_up
Recommended Articles
Page :