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 :
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.