Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Converting Objects to Primitives

Why, when using Symbol.toPrimitive, do we have to return a primitive of the same type as the hint? For example, when using valueOf() and toString(), we can return for example a string for the "number" hint, or for example a number for the "string" hint. But in Symbol.toPrimitive this does not work, as if after the return there is another typecast.

let user = {
  name: 'John',
  money: 1000,

  [Symbol.toPrimitive](hint) {
    return hint == 'string' ? 123 : `this.money`;
  },
};

alert(user); // 123
alert(+user); // NaN

Here we get 123 for string hint and NaN for number hint.

If we do it like this:

let user = {
  name: 'John',
  money: 1000,

  toString() {
    return 123;
  },

  valueOf() {
    return '123';
  },
};

alert(user); // 123
alert(+user); // '123'

As a result, we will get 123 for string hint and '123' for number hint.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!