Last active
February 24, 2023 06:14
-
-
Save AnshKapoor/955a1a537113fed7df2e9056459f12bc to your computer and use it in GitHub Desktop.
An example to demonstrate the usage of Symbol.toPrimitive
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
// Taken from https://h3manth.com/posts/Well-known-symbols/ | |
class Life { | |
[Symbol.toPrimitive](hint) { | |
switch (hint) { | |
case "number": | |
return 100; | |
case "string": | |
return "Hundred"; | |
case "default": | |
return true; | |
} | |
} | |
} | |
const myLife = new Life(); | |
console.log(+myLife); // 100 | |
console.log(`${myLife}`); // "Hundred" | |
console.log(myLife + 0); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without the
Symbol.toPrimitive
the output will be