DEV Community

Siddharth
Siddharth

Posted on

The "well-known" Symbols in JavaScript

You might have stumbled upon the weird @@thingies in JavaScript before. Maybe you saw an @@iterator or an @@match somewhere

These aren't valid JavaScript (@@iterator would throw an error). They are actually internal Symbols used in
JavaScript. They are used to implement features like iteration, instanceOf, and such internally. They actually might get removed or changed

For example: you can set @@isConcatSpreadable to stop .concat from spreading arrays.

const customArray = [1, 2, 3];
customArray[Symbol.isConcatSpreadable] = false;

const concatenatedArray = [4, 5, 6].concat(customArray);
console.log(concatenatedArray); // Output: [4, 5, 6, [1, 2, 3]]
Enter fullscreen mode Exit fullscreen mode

Another one, a more useful one, is @@iterator it is used internally to define iteration - ie in for loops.

const customIterable = {
    [Symbol.iterator]() {
        return {
            next() {
                // Infinite loop
                return { value: 'anything', done: false }
                // return {done: true} when done
            }
        }
    }
}

for (const item of customIterable) {
    console.log(item);
}
Enter fullscreen mode Exit fullscreen mode

@@match can also have potential use cases:

class CustomDateMatcher {
    [Symbol.match](str) {
        // ...logic...
    }
}

const str = '21st of March';
console.log(str.match(new CustomDateMatcher('21/03'))); // Custom pattern matching result
Enter fullscreen mode Exit fullscreen mode

More notable mentions:

  • @@toStringTag for converting an object to a string
  • @@toPrimitive for converting an object to a primitive
  • @@search for .search()
  • Full list on MDN

Do you have any ideas / suggestions for how to make use of this in code? Leave a comment!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.