Why doesn't it print a number?
-
let salaries= { John:100, Ann:160, Pete:130, } let sum; let summ=(obj)=>{ for(key in obj) { sum+=obj[key]; } } summ(salaries); console.log(typeof(sum)); console.log(sum);
Type writes: number
And on the output: NaN
Why?JavaScript Anonymous, Dec 7, 2020 -
Because sum initially contains undefined.
Try this:
let sum = 0;
Grayson Clements -
We need to initialize the variable sum.
let sum = 0;
Anonymous -
The initial value of sum is not set.
Well, the solution itself is not the best. Using an external variable in a function unnecessarily is bad manners.
let summ = (obj) => {
let sum = 0
for (key in obj) {
sum += obj[key]
}
return sum
}
let sum = summ(salaries)Anonymous -
Rewrite the cycle like this and see.
for (key in obj) {
console.log(sum, obj[key])
sum += obj[key];
}
Also read MDN what the for in loop outputs and how it differs from
Object.keys ()
And this is it
https://www.oreilly.com/library/view / you-dont-know ...Anonymous
4 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!