Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

279
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda