Code is not giving the appropriate result

This code below outputs 1

const array = [0, null, undefined, 1, 2, 3];
function countTruthy() {
let count = 0;
for (let each of array) {
if (each) {
count++;
return count;
}
}
}
console.log(countTruthy(array));

//But this block of codes below works according to MOSH’s tutorial on Javascript. I simply want to know how the curly braces affected the code please

whilw this outputs 3

const array = [0, null, undefined, 1, 2, 3];
function countTruthy() {
let count = 0;
for (let each of array) if (each) count++;
return count;
}
console.log(countTruthy(array));

Since the return statement is part of the code block inside the if statement (and the codeblock inside the for loop btw) your function is terminated as soon as the first truthy value is found. Thus 1 is returned as the result.

You need to code the return statement outside the loop’s code block.

1 Like

Thanks a lot Sam. This is very helpful