Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Created March 3, 2024 12:08
Show Gist options
  • Save MarwanShehata/e9d57fe39ee28aa5f0e821ffd3981dbd to your computer and use it in GitHub Desktop.
Save MarwanShehata/e9d57fe39ee28aa5f0e821ffd3981dbd to your computer and use it in GitHub Desktop.
You can implement custom behaviors for operators and methods using Symbols. For example, you can use the Symbol.toPrimitive well-known symbol to define how an object should be converted to a primitive value
const obj = {
[Symbol.toPrimitive]: function (hint) {
if (hint === "number") {
return 42;
} else if (hint === "string") {
return "Hello";
} else {
return true;
}
},
};
console.log(+obj); // 42
console.log(`${obj}`); // "Hello"
console.log(obj === true); // false
console.log(obj[Symbol.toPrimitive]()); // true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment