The term "well-known symbol" refers to built-in symbols that are used by some underlying JavaScript algorithms. You can also use these in your objects and/or classes to hook into a JavaScript object's lifecycle and control various aspects of it.
For example, if you implement the well-known symbol Symbol.toPrimitive()
as a class method, then you can control what value is returned when the class instance is coerced to another value:
// ES6+ class Foo { [Symbol.toPrimitive](hint) { if (hint === 'number') { return 1234; } return null; } } const foo = new Foo(); console.log(Number(foo)); // 1234
It can be implemented in the same way in an object literal:
// ES6+ const obj = { [Symbol.toPrimitive](hint) { if (hint === 'number') { return 1234; } return null; } } console.log(Number(foo)); // 1234
For simplicity, a "well-known" symbol is sometimes shortened to "@@<name>" (using the double at sign). However, the double at sign itself is not valid JavaScript syntax, and is merely meant for a shorter reference to Symbol.<name>
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.