Created
March 3, 2024 12:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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