How to useES6 Symbols in Javascript

Symbols are a new primitive type introduced in ES6, and they are often used to add unique properties to objects, ensuring that property names do not collide with other properties. This approach leverages Symbols to add a method to the String class.

Example: This example demonstrates how to use Symbols to add a method to the String class to calculate the sum of the lengths of two strings.

JavaScript
// Input string
let str1 = "Hello";
let str2 = "World!";

// Display input string
console.log(str1);
console.log(str2);

// Define a unique Symbol
const sumOfLengthSymbol = Symbol('sumOfLength');

// Define custom method using Symbol
String.prototype[sumOfLengthSymbol] = function(arg) {
    return this.length + arg.length;
};

// Run custom method
function customMethodWithSymbolExample() {
    // Apply custom method
    let res = str1[sumOfLengthSymbol](str2);

    // Display output
    console.log("Total length: " + res);
}

// Function call
customMethodWithSymbolExample();

Output
Hello
World!
Total length: 11





How to add method to String class in JavaScript ?

In this article, the task is to add a method to the String class in JavaScript. There are two approaches that are described with the proper examples: 

Similar Reads

Approaches to add Methods to String Class:

Table of Content Approach 1: Using Object.defineProperty() methodApproach 2: Using String.prototype.propertyName method Approach 3: Using ES6 ClassesApproach 4: Using ES6 Symbols...

Approach 1: Using Object.defineProperty() method

The Object.defineProperty() method is used to define a new property directly to an object or modify an existing property. It takes 3 arguments, the first is Object, the Second is propertyName, and the last is propertyDescription. In this example, the sum of the length of strings is returned....

Approach 2: Using String.prototype.propertyName method

The String.prototype.propertyName is used to add a new method to the String class. Define a method that takes arguments passed by the object and performs the desired operation. In this example, the sum of the length of strings is returned....

Approach 3: Using ES6 Classes

With ES6, you can use class syntax to define methods that will be added to the prototype of the String class. This approach allows for more structured and modern code....

Approach 4: Using ES6 Symbols

Symbols are a new primitive type introduced in ES6, and they are often used to add unique properties to objects, ensuring that property names do not collide with other properties. This approach leverages Symbols to add a method to the String class....