Answer the question
In order to leave comments, you need to log in
What are the advantages of using valueOf, toString, Symbol.toPrimitive?
Why are there valueOf
, toString
, Symbol.toPrimitive
, if it's easier and simpler to convert an object to the desired data type?
For example:
let a = {};
console.log(a); //объект --> string
a = +a; //объект --> number
Symbol.toPrimitive
? What exactly are their benefits?let user = {
name: "John",
money: 1000,
[Symbol.toPrimitive](hint) {
alert(`hint: ${hint}`);
return hint == "string" ? `{name: "${this.name}"}` : this.money;
}
};
// демонстрация результатов преобразований:
alert(user); // hint: string -> {name: "John"}
alert(+user); // hint: number -> 1000
alert(user + 500); // hint: default -> 1500
Answer the question
In order to leave comments, you need to log in
You have some kind of porridge.
> if you can convert the object to the desired data type easier and simpler
So these methods will implicitly call the same `toString`, `valueOf` and `Symbol.toPrimitive`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question