Skip to content

Instantly share code, notes, and snippets.

@AnshKapoor
Last active February 24, 2023 06:14
Show Gist options
  • Save AnshKapoor/955a1a537113fed7df2e9056459f12bc to your computer and use it in GitHub Desktop.
Save AnshKapoor/955a1a537113fed7df2e9056459f12bc to your computer and use it in GitHub Desktop.
An example to demonstrate the usage of Symbol.toPrimitive
// 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
@AnshKapoor
Copy link
Author

Without the Symbol.toPrimitive the output will be

 NaN 
[object Object]
[object Object]0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment