“This is the 30th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

⭐ ⭐

Difficulty rating is subjective, the highest five stars, the lowest one star, do not spray.

A: Symbol is a new JS feature in ES6. Symbol is a basic data type that represents unique values to prevent object attribute name conflicts.

An overview of the

Object attribute names in ES5 are all strings, which can easily cause attribute name conflicts. For example, if you use an object provided by someone else and want to add a new method to the object, the name of the new method may conflict with that of the existing method. It would be nice if there were a mechanism to ensure that each property name was unique, preventing property name conflicts at all. This is why ES6 introduced Symbol.

ES6 introduces a new primitive data type, Symbol, that represents unique values. It is the seventh data type in JavaScript, with undefined, NULL, Boolean, String, Number, and Object being the first six.

The Symbol value is generated by the Symbol function. This means that object property names can now be of two types: the original string and the new Symbol type. Attribute names that belong to the Symbol type are unique and are guaranteed not to conflict with other attribute names.

The basic use

const symbol1 = Symbol(a)const symbol2 = Symbol(42)
const symbol3 = Symbol('foo')

console.log(typeof symbol1)    // 'symbol'

console.log(symbol2 === 42)    // false

console.log(symbol3.toString()) // 'Symbol(foo)'

console.log(Symbol('foo') = = =Symbol('foo')) // false
Copy the code

Although the call to Symbol() makes it look like an object, Symbol is actually a JavaScript primitive data type. Using new as a constructor for Symbol raises an error.

new Symbol(a)// Uncaught TypeError: Symbol is not a constructor
Copy the code

Prevents object attribute name conflicts

const obj = {
  name: 'lin'.age: 18
}

obj.name = 'xxx'   // assign obj.name to override the previous name
console.log(obj) // { name: 'xxx', age: 18 }
Copy the code
const obj = {
  name: 'lin'.age: 18
}
const name = Symbol('name')

obj[name] = 'xxx'   // Use Symbol, not overwrite


console.log(obj)    // { name: 'lin', age: 18, Symbol(name): 'xxx' }
console.log(obj.name)  // 'lin'
console.log(obj[name]) // 'xxx'
Copy the code

For more information, visit MDN

This is the 30th day of alynn’s continuous blog post, exporting insight techniques, goodbye ~

The last:

“Front-end Daily Question (1)” What is BigInt? What problem was solved?

Next up:

What is the difference between JS primitive types and reference types?