educative.io

Educative

Sum all values in an object

Can someone help me to pass this? This is only returning the first value. And when I try to use += it shows an error.

function addValues(obj) {
for (let key in obj) {
let sum = obj[key];
return sum;
}
}


Type your question above this line.

Course: https://www.educative.io/collection/5679346740101120/5720605454237696
Lesson: https://www.educative.io/collection/page/5679346740101120/5720605454237696/5647906690301952

Hello @Lepros

Following is the correct code:

function addValues(obj) {
    let sum = 0;
    for (let key in obj) {
        sum = sum + obj[key];
    }
    return sum;
}

Issue in your implementation is that you are just returning the number in first key of the object. You are essentially not summing up the numbers.

Hope this helps!

1 Like

Thank you for all your help. I noticed I had some of the same mistakes as my other post’s problem. I need to remember to declare the variable and return it outside of the loop. Thank you!