Programming Tutorials

Symbol() function in JavaScript

By: Stella in Javascript Tutorials on 2023-04-25  

Symbol() is a built-in function in JavaScript that returns a unique symbol value. Symbols are a new primitive data type introduced in ECMAScript 6, which can be used as keys in objects, allowing for more efficient property lookup and avoiding naming collisions.

Here's an example of how to create and use a symbol:

const mySymbol = Symbol('mySymbol');
const obj = {};
obj[mySymbol] = 'Hello, world!';
console.log(obj[mySymbol]); // Output: 'Hello, world!'

In this example, mySymbol is a new symbol value with a description of 'mySymbol'. This description is useful for debugging purposes, but doesn't affect the value of the symbol itself. The obj object is then created, and the mySymbol symbol is used as a key to store the string 'Hello, world!'. This string can then be accessed using the mySymbol key.

One important thing to note is that symbols are always unique, even if they have the same description. For example:

const mySymbol1 = Symbol('mySymbol');
const mySymbol2 = Symbol('mySymbol');
console.log(mySymbol1 === mySymbol2); // Output: false

ven though mySymbol1 and mySymbol2 have the same description, they are two separate symbol values and are not equal to each other.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)