DEV Community

Siddharth
Siddharth

Posted on

10 1 1 1 1

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay