symbol(JavaScript Variable data type)

Japanese version.

Symbol is a new data type introduced in ECMAScript 6 (ES6) that is used to represent a unique identifier. It is a primitive data type, like strings and numbers, and is immutable with a unique value.

A symbol value is created by calling the Symbol() function.

const mySymbol = Symbol();

You can also pass an optional description as an argument to the Symbol() function, which is useful for debugging because it is displayed by the toString() method.

const mySymbol = Symbol('This is a symbol');

console.log(mySymbol.toString()); // "Symbol(This is a symbol)"

The main use of symbol is as a property name in objects. When used as a property name, the property can only be accessed using the [ ] operator.

const mySymbol = Symbol('This is a symbol');
const myObj = {};

myObj[mySymbol] = 'Hello, world!';
console.log(myObj[mySymbol]); // "Hello, world!"

symbol is used to represent unique and immutable values. By using symbol as a property name, you can create unique property names that do not collide with existing ones. symbol is also used to implement private properties and methods.

When comparing symbol values, true is returned only if they refer to the same symbol. This is because symbol values are unique, so symbols created separately have different values.

Here is an example of comparing symbol values:

const symbol1 = Symbol('foo');
const symbol2 = Symbol('foo');

console.log(symbol1 === symbol2); // false

In this example, symbol1 and symbol2 are symbols with the same description, but they have different values, so false is returned.

On the other hand, the Symbol.for() method registers a symbol in a global symbol registry, so symbols with the same description have the same value. Therefore, in the following code, symbol3 and symbol4 refer to the same symbol, so true is returned.

const symbol3 = Symbol.for('foo');
const symbol4 = Symbol.for('foo');

console.log(symbol3 === symbol4); // true

Although Symbol.for() can create global symbols, it is recommended to use the regular Symbol() method to create symbols within as long as the names do not collide.



JavaScript Articles