Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading