How to use ES6 Symbols In Javascript
- We firstly create an object TShirtSizes
- Inside the object, we define symbols for each size using Symbol()
- The orderTShirt function takes a size argument.
- We had performed a strict comparison (!==) between the argument and each enum member (symbol) to ensure a valid size is provided.
- If a valid size is used, then the order is been processed.
- If anyone attempt to use an invalid string value (e.g. “Medium”) throws an error due to the strict comparison with symbols.
Example: This example shows how to create an enum using ES6 Symbols.
const TShirtSizes = {
SMALL: Symbol('Small'),
MEDIUM: Symbol('Medium'),
LARGE: Symbol('Large'),
EXTRA_LARGE: Symbol('Extra Large')
};
function orderTShirt(size) {
if (size !== TShirtSizes.SMALL &&
size !== TShirtSizes.MEDIUM &&
size !== TShirtSizes.LARGE &&
size !== TShirtSizes.EXTRA_LARGE) {
throw new Error('Invalid T-Shirt size!');
}
console.log(`Processing order for
size: ${String(size)}`);
}
orderTShirt(TShirtSizes.MEDIUM);
Output
Processing order for size: Symbol(Medium)
Let’s see if we try to provide a string argument:
const TShirtSizes = {
SMALL: Symbol('Small'),
MEDIUM: Symbol('Medium'),
LARGE: Symbol('Large'),
EXTRA_LARGE: Symbol('Extra Large')
};
function orderTShirt(size) {
if (size !== TShirtSizes.SMALL &&
size !== TShirtSizes.MEDIUM &&
size !== TShirtSizes.LARGE &&
size !== TShirtSizes.EXTRA_LARGE) {
throw new Error('Invalid T-Shirt size!');
}
console.log(`Processing order for
size: ${String(size)}`);
}
orderTShirt("Medium");
Output:
How to Create Enums in JavaScript ?
An enum, short for “enumerated type”, is a special data type in programming languages that allows us to define a set of named constants. These constants are essentially unchangeable variables that represent a fixed collection of possible values. Each contants can be accessed by its name. Enums are very similar to constants but they offer more data structure. we will learn about creating enums in JavaScript, exploring their significance in code organization and readability, along with practical implementation approaches using closures and other techniques.
These are the following approaches:
Table of Content
- Using Object Literal with Object.freeze()
- Using ES6 Symbols
- Using Closures