Symbols Flashcards
How do you create symbol?
const sym = Symbol(‘symbol’)
the built in Symbol function
paramater is optional and used for debugging purposes
How are symbols similar to objects?
compared by location not values so you can use them for values that need to be unique even if compared against themselves
How to access the Symbol() parameter?
const sym = Symbol(‘symbol’)
sym.description
-> ‘symbol’
Use case for symbols?
values for constants:
you may have two const vars mood_blue and color_blue with the same value of ‘string’. you can accidentally mix these up since the values are equal when compared, even though they represent different data.
using symbols would prevent them from evaluating to equal if compared
unique property keys:
properties as symbols help avoid clashes between base-level and meta-level properties.
const point = {
x: ‘2’,
y: ‘5’,
toString() {
return `${this.x}, ${this.y}
}
toString is a meta property, created by ECMAScript while x and y are base properties created by the user.