const id = Symbol("id");
const user = {
name: "John",
age: 30,
[id]: 12345
};
console.log(user[id]); // 12345
console.log(user.id); // undefined
console.log(user); // { name: 'John', age: 30, [Symbol(id)]: 12345 }
Output:
12345
undefined
{ name: 'John', age: 30, [Symbol(id)]: 12345 }
Brief Explanation:
use of symbols as unique property keys in objects. In this code, a symbol is
created using `Symbol("id")`, which serves as a unique identifier for the `id`
property in the `user` object. The `user` object has three properties: `name`, `age`,
and a symbol-based property `[id]`.
When accessing the symbol-based property using `user[id]`,
it correctly retrieves the value `12345`. However, trying to access
it using `user.id` returns `undefined` because the property key is a symbol,
not a string.
Finally, logging the entire `user` object shows that it contains the symbol-based property
along with the other properties.
No comments:
Post a Comment