Symbols are basically a new primitave type such as numbers, strings booleans.

They provide a unique identifier

use cases

  • can add properties to objects that you know is definitally unique

Code

Symbols Basics


Creating a Symbol

//Symbols in ES6

//In ES6 we can use the Symbol Primitave, and it only accepts one parameter which you cant really use except for debugging

//Creating a symbol
let symbol = Symbol('debug');
console.log(symbol.toString());

1
2
3
4
5
6
7
8

Using Symbols with Objects

//Symbols in ES6

//In ES6 we can use the Symbol Primitave, and it only accepts one parameter which you cant really use except for debugging

//Creating a symbol
let symbol = Symbol('debug');


//Defining our object using a dynamic property

let obj = {
  name: 'brad',
  [symbol]: 22
}

console.log(obj);

console.log(obj[symbol]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Shared Symbols


Example : Creating shared id's amongs symbols

//Symbols in ES6 - The Symbol for method

//Using shared id's amongs symbols

let symbol1 = Symbol.for('age');
let symbol2 = Symbol.for('age');

console.log(symbol1 == symbol2);

1
2
3
4
5
6
7
8
9

Example : Creating reuse keys with symbols

//Symbols in ES6 - The Symbol for method


let symbol1 = Symbol.for('age');
let symbol2 = Symbol.for('age');

let person = {
  name: 'Violet'
};

function makeAge(person) {
  //ageSymbol will not be accessable because it is within the functional scope
  let ageSymbol = Symbol.for('age');
  person[ageSymbol] = 27
}

//Call the makeAge function
makeAge(person);

console.log(person[symbol1]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Example Two : Using symbols


//Symbols in ES6


let symbol = Symbol.for('age');

let person = {
  name: 'Violet',
  age: 30
};

function makeAge(person) {
  let ageSymbol = Symbol.for('age');
  person[ageSymbol] = 27
}

makeAge(person);

console.log(person[symbol]); // Logs 27
console.log(person["age"]);  // Logs 30


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Last Updated: 8/13/2019, 6:55:26 PM