I'm trying to put on the screen that items from a list that I have done. I came up with this function:
function countDone() {
let numberOfDone = 0
for (let i = 0; i < todoList.length; i++) {
if (todoList[i].isDone === true) {
numberOfDone = numberOfDone + 1
}
return numberOfDone
}
}
function printCountDone() {
let f = countDone()
document.querySelector('#todo-done').innerHTML = f
}
I don't know if the function is wrong or if I'm just calling it at the wrong place. I saw some similar posts here, but I couldn't understand (I'm a newbie, sorry in advance) Here is the codepen link: https://codepen.io/lodesousa/pen/jOLOeLr
@Chris G has already covered this in their comments, but I wanted to explore what's happening with you in greater depth.
Here's the code you have, in plain English:
function countDone:
create variable "numberOfDone" and set to 0
iterate over all todos. for each todo:
if the todo is done:
increase variable "numberOfDone" by 1
return variable numberOfDone
end iteration
end function
Spot the error? Check out the indentation. Spoiler: The function isn't returning anything.
You're returning numberOfDone every iteration of the for loop rather than right at the end of the function like you want.
Returning a value at the wrong point in a function is an incredibly common programming error – I'd bet every programmer has faced this at one point. That's something that you should think about going forward: checking if a function returns anything is an excellent starting place when debugging functions.
Anyway, cheers, and welcome to Stack Overflow! Congrats on your first question!