Symbols for Unique Identifiers
123456789101112const id1 = Symbol("userID"); const id2 = Symbol("userID"); const user = { name: "Alice", [id1]: 101, [id2]: 202 }; console.log(user[id1]); // 101 console.log(user[id2]); // 202 console.log(JSON.stringify(user)); // { name: 'Alice', [Symbol(userID)]: 101, [Symbol(userID)]: 202 }
Symbols are a primitive data type in JavaScript used to create unique identifiers. When you create a symbol using Symbol("description"), each symbol is guaranteed to be unique—even if the descriptions are the same. This makes symbols especially useful for adding properties to objects when you want to avoid accidental name collisions with other code or libraries.
You should use symbols when you need to add a property to an object that should not interfere with existing or future property names. Unlike strings, symbols are not enumerable in standard loops like for...in, so they are often used to define special object properties that are meant for internal use or to add metadata.
Symbols are commonly used in situations such as building libraries, frameworks, or when you want to ensure that certain object keys remain private or do not clash with others. By using symbols, you protect your data from being accidentally overwritten or accessed by unrelated code.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 6.25
Symbols for Unique Identifiers
Svep för att visa menyn
123456789101112const id1 = Symbol("userID"); const id2 = Symbol("userID"); const user = { name: "Alice", [id1]: 101, [id2]: 202 }; console.log(user[id1]); // 101 console.log(user[id2]); // 202 console.log(JSON.stringify(user)); // { name: 'Alice', [Symbol(userID)]: 101, [Symbol(userID)]: 202 }
Symbols are a primitive data type in JavaScript used to create unique identifiers. When you create a symbol using Symbol("description"), each symbol is guaranteed to be unique—even if the descriptions are the same. This makes symbols especially useful for adding properties to objects when you want to avoid accidental name collisions with other code or libraries.
You should use symbols when you need to add a property to an object that should not interfere with existing or future property names. Unlike strings, symbols are not enumerable in standard loops like for...in, so they are often used to define special object properties that are meant for internal use or to add metadata.
Symbols are commonly used in situations such as building libraries, frameworks, or when you want to ensure that certain object keys remain private or do not clash with others. By using symbols, you protect your data from being accidentally overwritten or accessed by unrelated code.
Tack för dina kommentarer!