Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda