Search This Blog

2024/03/27

Javascript:Symbol Introduction

The JavaScript ES6 introduced a new primitive data type called Symbol.
Symbols are immutable (cannot be changed) and are unique.

Code:
// two symbols with the same description

const value1 = Symbol('hello');
const value2 = Symbol('hello');
console.log(value1 === value2); // false

Creating Symbol:
Symbol() function is used to create a Symbol.

Code:
// creating symbol
const x = Symbol()
typeof x; // symbol

An optional string can be passed as its description in to Symbol() function:

Code:
const x = Symbol('hey');
console.log(x); // Symbol(hey)

Access Symbol Description:
To access the description of a symbol, we use the . operator.

Code:
const x = Symbol('hey');
console.log(x.description); // hey

Using Symbol as Object Key:
You can add symbols as a key in an object using square brackets [].

Code:
let id = Symbol("id");
let person = {
name: "Jack",

// adding symbol as a key
[id]: 123 // not "id": 123
};
console.log(person); // {name: "Jack", Symbol(id): 123}

Symbolic Properties of object are not iterable:

Code;
let id = Symbol("id");
let person = {
name: "Jack",
age: 25,
[id]: 12
};
// using for...in
for (let key in person) {
console.log(key);
}
Output:
name
age

Mixing Symbol & string of same name in object key:

Code:
let person = {
name: "Jack",
};

// creating Symbol
let id = Symbol("id");

// adding symbol as a key
person[id] = 12;
person["id"] = 786;

console.log(person[id])
console.log(person['id'])
Output:
12
786

Symbol Methods:
There are various methods available with Symbol.

Below is list of common symbol methods.
1) for():Searches for existing symbols
2) keyFor():Returns a shared symbol key from the global symbol registry.
3) toSource():Returns a string containing the source of the Symbol object
4) toString():Returns a string containing the description of the Symbol
5) valueOf():Returns the primitive value of the Symbol object.


Code:
// get symbol by name
let sym = Symbol.for('hello');
let sym1 = Symbol.for('id');

// get name by symbol
console.log( Symbol.keyFor(sym) ); // hello
console.log( Symbol.keyFor(sym1) ); // id

Symbol Properties:
Here is list of common symbol properties & there description.

1) asyncIterator:Returns the default AsyncIterator for an object
2) hasInstance:Determines if a constructor object recognizes an object as
its instance
3) isConcatSpreadable:Indicates if an object should be flattened to its
array elements
4) iterator:Returns the default iterator for an object
5) match:Matches against a string
6) matchAll:Returns an iterator that yields matches of the regular
expression against a string
7) replace:Replaces matched substrings of a string
8) search:Returns the index within a string that matches the regular
expression
9) split:Splits a string at the indices that match a regular expression
10) species:Creates derived objects
11) toPrimitive:Converts an object to a primitive value
12) toStringTag:Gives the default description of an object
13) description:Returns a string containing the description of the symbol

Code:
const x = Symbol('hey');

// description property
console.log(x.description); // hey

const stringArray = ['a', 'b', 'c'];
const numberArray = [1, 2, 3];

// isConcatSpreadable property
numberArray[Symbol.isConcatSpreadable] = false;

let result = stringArray.concat(numberArray);
console.log(result); // ["a", "b", "c", [1, 2, 3]]

No comments:

Post a Comment