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

268
Vistas
why is undefined returned if type coercion is executing

I'm trying to set a value to an undefined variable, the type changes but the value doesn't. Why is it happening?

let average; // is it a must to do 'average = 0;' for it work?
for (const [oddName, odd] of Object.entries(game.odds)) {
    // console.log(typeof oddName); // is a str
    console.log(typeof odd); // is a num
    console.log(typeof average);
    average += odd;
    // console.log(typeof average); // 'average' does change to a number
    console.log(average); //returns NaN
}

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

You are adding a number with an undefined value. when adding undefined with a number it will make NaN.

maybe only the assignment operator (=) would work for you

enter image description here

about 4 years ago · Santiago Gelvez Denunciar

0

You can simplify this further, and observe the effect:

let a;
console.log(a, " is of type ", typeof a);
a += 1;
console.log(a, " is of type ", typeof a);

let b = 0;
console.log(b, " is of type ", typeof b);
b += 1;
console.log(b, " is of type ", typeof b);

Note that a starts off as undefined, because we didn't give it a value. When we add 0, it is converted to type "number", but there is no answer to the sum "unknown value plus one", so it is given the special value NaN.

If we set it to 0, it is already a number; but more importantly, the sum "zero plus one" has a sensible answer, so we get the result 1.

about 4 years ago · Santiago Gelvez Denunciar

0

you should assign average to 0 in the first line. Because undefined + number = NaN;

about 4 years ago · Santiago Gelvez Denunciar
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