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.
// 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: