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

264
Views
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 answers
Answer question

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 Report

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 Report

0

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

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