Does the condition in a for loop need to be true in order for the code to execute?

Hello,

This code is from the recursion challenge in basic JavaScript. I actually have a question about the code using for loops before the concept of recursion is used:

function multiply(arr, n) {
    let product = 1;
    for (let i = 0; i < n; i++) {
      product *= arr[i];
}
    return product;
}

console.log(multiply([1, 2, 3, 4], 0))

In this particular situation, i < n is false (given that n = 0). Does this mean that the code in the curly braces won’t execute, and that the product value is equal to 1? Or does it still execute so that product *= arr[i] = product * arr[0] which is 1 *1 = 1. I know the answer is the same but I’m wondering how to think about this properly.

Add a console.log inside the for loop and that will tell you whether the code inside the loop ran when n is 0.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.