JavaScript Symbols are a new type of primitive data type introduced in the ES6 version of the language. They are used to represent unique values that can be used as identifiers or keys in objects. They are also used to create private properties and methods in classes.
// Create a Symbol
const mySymbol = Symbol();
console.log(mySymbol);
// expected output: Symbol()
// Create a global Symbol
const myGlobalSymbol = Symbol('myGlobalSymbol', { global: true });
console.log(myGlobalSymbol);
// expected output: Symbol(myGlobalSymbol)
// Create a constant
const MY_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
console.log(MY_CONSTANT);
// expected output: Symbol(MY_CONSTANT)
const mySymbol = Symbol();
const myObject = {
[mySymbol]: 'Hello World'
};
console.log(myObject[mySymbol]);
// expected output: 'Hello World'
const mySymbol = Symbol();
const myObject = {
[mySymbol]: 'Hello World'
};
// Private property is not enumerable
console.log(Object.keys(myObject));
// expected output: []
// Create a constant
const MY_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
// Create another constant
const MY_OTHER_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
console.log(MY_CONSTANT === MY_OTHER_CONSTANT);
// expected output: false
const mySymbol = Symbol();
const myObject = {
[mySymbol]: 'Hello World'
};
console.log(myObject[mySymbol]);
// expected output: 'Hello World'
// Create a constant
const MY_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
// Create another constant
const MY_OTHER_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
console.log(MY_CONSTANT === MY_OTHER_CONSTANT);
// expected output: false
// Create a constant
const MY_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
// Create another constant
const MY_OTHER_CONSTANT = Symbol('MY_CONSTANT', { constant: true });
console.log(MY_CONSTANT === MY_OTHER_CONSTANT);
// expected output: false