Symbol Object in JavaScript. Code example open

Symbol Object in JavaScript. Code example

The Symbol type constructor is used to define a symbol. For example, let’s create a simple symbol:

const alex = Symbol("Alexander");
console.log(alex);   // Symbol(Alexander)

And each character is unique. So, let’s try to create two identical symbols:

    const alex = Symbol("Alexander");
    console.log(alex);   // Symbol(Alexander)

    const alx = Symbol("Alexander");
    console.log(alx); // Symbol(Alexande)

    console.log(alex == alx);      // false
    console.log(alex === alx);     // false

Despite the fact that both symbols created above in the prime are initialized with the same value, both equality and equivalence operators return false when comparing these symbols. That is, characters are always unique.

The main area of application of symbols is the definition of object property identifiers. That is, in short, symbols allow you to avoid situations where several properties of an object have the same name.

Apply symbols:

    const company = {
        [Symbol("Tom")]: "senior",
        [Symbol("Sam")]: "junior",
        [Symbol("Tom")]: "junior"
    }

    const developers = Object.getOwnPropertySymbols(company);//function to get all characters from an object
    for (developer of developers) {
        console.log(`${developer.toString()} - ${company[developer]}`);
    }
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation