How do you create a loop in JavaScript that runs 5 times?
a) for (let i = 0; i < 5; i++) { … }
b) while (i < 5) { … }
c) for (i <= 5) { … }
d) loop (i < 5) { … }
Answer:
a) for (let i = 0; i < 5; i++) { … }
Explanation:
In JavaScript, the for
loop is a common way to iterate a block of code a specified number of times. The syntax includes initialization, a condition, and an increment.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4