I
I
Ivanushka2552021-06-09 11:58:28
JavaScript
Ivanushka255, 2021-06-09 11:58:28

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


Is it really necessary to always write these cumbersome constructions of object and symbol methods 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

1 answer(s)
L
Lynn "Coffee Man", 2021-06-09
@Ivanushka255

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 question

Ask a Question

731 491 924 answers to any question