Let’s learn about JavaScript symbols.
Symbols are used to generate unique and universal symbol values .
Explanation and usage of symbols
Symbol
is used to generate unique and immutable symbol values.
Symbols Symbol
can be generated by methods. The argument is a description of the symbol, and symbols created separately with the same value are considered different. Symbols can be created without arguments.
Symbol(symbol description);
Symbol
const
You can make these symbol values immutable by using and .
const MY_SYMBOL = Symbol();
You can also Symbol
use to define properties of objects.
const MY_SYMBOL = Symbol();
const obj = {
[MY_SYMBOL]: 'hello'
};
console.log(obj[MY_SYMBOL]); // 'hello'
By using symbols, you
can identify variables just by name without having to assign values like 0, 1, etc !
Use symbols for if conditional branching
Symbol
You can use the if statement to write conditional branching based on the properties defined in .
const MY_SYMBOL = Symbol();
let mySymbol = MY_SYMBOL;
if (mySymbol === MY_SYMBOL) {
console.log('The specified symbol.');
} else {
console.log('Not the specified symbol.');
}
Summary of “Learn to use Symbol”
” Learn how to use Symbol ” is summarized below.
- JavaScript
Symbol
is used to generate unique and immutable symbol values. Symbol
can be used to distinguish it from other properties.Symbol
Properties defined in can use if statements and conditional branches just like regular properties.const
By using ,Symbol
you can make the value of .
Symbol
can be used to generate unique and immutable symbol values.
These symbolic values are often used to define properties of objects because they can be distinguished from other properties.
Comments