javascript / expert
Snippet
Controlling Subclassed Array Species Transformations via Symbol.species
When subclassing built-in data structures like Array, derived methods such as .map(), .filter(), or .slice() default to returning new instances of the subclass. Defining a static getter for Symbol.species allows derived classes to override this behavior, directing array transformation methods to return standard Array instances instead of inheriting custom subclass state and methods.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class AuditList extends Array {static get [Symbol.species]() {return Array;}logAudit(action) {this.push(`[${new Date().toISOString()}] ${action}`);}}const audit = new AuditList();audit.logAudit('USER_LOGIN');const filtered = audit.map(entry => entry.toUpperCase());console.log(audit instanceof AuditList);console.log(filtered instanceof AuditList);console.log(filtered instanceof Array);
nodejs
Breakdown
1
class AuditList extends Array
Extends the native JavaScript Array prototype to add specialized domain logging methods.
2
static get [Symbol.species]()
Well-known Symbol constructor getter that specifies which constructor is used for derived objects.
3
return Array;
Forces methods like .map() to instantiate standard Array objects instead of new AuditList instances.
4
audit.map(...)
Executes array transformation while yielding a base Array result, avoiding unwanted subclass overhead or state leaks.