DEV Community

Cover image for JS Symbol, what the heck?

JS Symbol, what the heck?

Romain Trotard on October 27, 2021

Among the primitive data type, you may have already heard about Symbol. But you're asking yourself what is it? When is it useful? When are they cur...
Collapse
 
jonrandy profile image
Jon Randy 🎖️

Great explanation! Another use case for Symbols is safely extending prototypes (Array, String, Number, etc.) - I built a library (Metho) that helps to do this kind of thing easily. Check it out if you want to see another way Symbols can be used

Collapse
 
romaintrotard profile image
Romain Trotard

Oh thank you for the additional information. I check your library asap :)

Collapse
 
danielwebtd profile image
WEBTD • Edited

In the "same value in iframe" section both return false, what am I doing wrong?

// Will print false!
console.log(iframeWindow.Symbol === Symbol);

// But will print true!
console.log(iframeWindow.sharedSymbol === Symbol.for('Shared symbol'));
Collapse
 
romaintrotard profile image
Romain Trotard

Hello. Do you have some code to share ?
I have made a codesandbox where you can see the behavior: codesandbox.io/s/iframe-example-fo...

Collapse
 
danielwebtd profile image
WEBTD

Hi, it worked, thanks, I just needed to use load to wait for the iframe to load.
iframe.addEventListener('load', () => {
// do something
});

Collapse
 
zyabxwcd profile image
Akash • Edited

one question.
why did you write the last example as
class Computer {
constructor() {
this[Symbol.toStringTag] = "Computer";
}
}
and not like
class Computer {
[Symbol.toStringTag] = "Computer";
}

Collapse
 
romaintrotard profile image
Romain Trotard

I write like this because if I'm not mistaken the public class field will be available in ES2022.
Or we currently can use it thanks to babel plugin @babel/plugin-proposal-class-properties

Collapse
 
jzombie profile image
jzombie • Edited

Great article! Really enjoyed the iterator and class toString methods you presented.

Collapse
 
romaintrotard profile image
Romain Trotard

Thank you. Glad you liked it :)

Collapse
 
zyabxwcd profile image
Akash

wow. you used some advanced syntax and techniques there. I read about Symbols way back but never used them and neither do people generally know about them as I have seen.

Collapse
 
romaintrotard profile image
Romain Trotard

Yep generally people doesn't know about Symbol, hoping my article will show that it's useful :)