Home >Web Front-end >JS Tutorial >What does symbol mean in js

What does symbol mean in js

下次还敢
下次还敢Original
2024-05-07 18:24:17889browse

Symbol is a unique identifier in JavaScript. It is used as an object attribute name to prevent naming conflicts. It is unique, immutable and private. It can be created and assigned through Symbol() and is only strictly equal to itself. Compare.

What does symbol mean in js

Symbol in JavaScript

Symbol is a primitive data type in JavaScript that represents a unique identifier . It was first introduced in the ES6 (ECMAScript 2015) release.

Usage:

Symbol is mainly used to create unique property names to avoid naming conflicts and enhance code readability.

Characteristics:

  • Uniqueness: Every Symbol is different, even if they have the same value.
  • Immutability: Once a Symbol is created, its value cannot be modified.
  • Privateness: Unlike regular properties, Symbol properties will not appear in regular iterations, such as for...in loops.
  • Assignment: Symbol can be assigned to variables like other primitive data types.

Create Symbol:

Use Symbol() function to create Symbol:

<code class="js">const mySymbol = Symbol();</code>

Compare Symbol:

Since Symbols are unique, they can only be strictly equal to themselves (===) Comparison:

<code class="js">console.log(mySymbol === mySymbol); // true
console.log(mySymbol === Symbol()); // false</code>

As Property name:

Symbol can be used as the name of an object's property, thus freeing it from naming conflicts:

<code class="js">const person = {
  [Symbol("name")]: "John Doe",
  age: 30
};

console.log(person[Symbol("name")]); // "John Doe"</code>

Other usage:

Symbol has other uses, including:

  • Create custom iterator interfaces
  • Identify private methods or properties
  • Enhance test readability and maintainability

The above is the detailed content of What does symbol mean in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does bom mean in jsNext article:What does bom mean in js