- Published at
- Updated at
- Reading time
Symbols are these relatively new types that were added to the language not too long ago. I have to say though that I'm not using them very often. Let's quickly recap with an MDN quote:
Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.
And this is how they work (shamelessly copied from MDN):
const symbol1 = Symbol(); const symbol2 = Symbol(42); console.log(typeof symbol1); // expected output: "symbol" console.log(symbol3.toString()); // expected output: "Symbol(foo)"
const a = Symbol(); a.foo = 'bar'; console.log(a.foo); // ?
The snippet above logs
undefined to the console. This shows that it is not possible to set new properties on a symbol. The runtime is not throwing an error though.
const a = 123; a.foo = 'bar'; console.log(a.foo); // undefined const b = 'baz'; b.length = 2; console.log(b.length); // 3
There are clearly not many use cases for setting a new or redefining a property on an e.g.
Edited: As the reddit user
pertheusual points out adding properties to primitives throws an exception in
- The navigation timing API includes the type of the current navigation
- Define where an element should be scrolled to using elem.scrollIntoView
- Is the module/nomodule bridge worth it?
- requestSubmit offers a way to validate a form before submitting it
- Optional chaining helps to avoid "undefined is not a function" exceptions