Home > Web Front-end > JS Tutorial > body text

What does symbol mean in js

下次还敢
Release: 2024-05-07 18:24:17
Original
792 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!