Lesson 5 of 15
For Loops
For Loops
The classic for loop has three parts: initializer, condition, and update:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// prints 0, 1, 2, 3, 4
let i = 0— runs once at the starti < 5— checked before each iteration; loop stops when falsei++— runs after each iteration
Summing Numbers
let total = 0;
for (let i = 1; i <= 10; i++) {
total += i;
}
console.log(total); // 55
for...of
for...of iterates over the values in an array:
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
Your Task
Write function sumTo(n) that returns the sum of all integers from 1 to n (inclusive). Use a for loop.
JavaScript loading...
Loading...
Click "Run" to execute your code.