For Loop
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 38 of 77.
Sometimes when programming it's necessary to perform same or almost the same operation a couple of times.
To prevent writing the same thing over and over again we can use Loops.
The for loop has the following syntax
for (let i = start; i < end; i++) {
code;
}The let i = start determines the initial value of i, i < end determines the condition for the loop to continue, and i++ increments i after each iteration. The i will receive all values from start to end (not including <strong>end</strong>) sequentially. For example:
for (let i = 0; i < 5; i++) {
console.log(i);
}It will execute the print statement 5 times:
0
1
2
3
4Loops have many use cases. For example let's sum all the number from 1 to 100:
let sum_numbers = 0;
for (let i = 1; i <= 100; i++) {
sum_numbers += i;
}
console.log(sum_numbers);This will first loop through all numbers between 1 to 100 (including 100) and sum all of them. Then it will print the sum_numbers variable
Challenge
BeginnerWrite a program that prints "Hello Coddy: " and the i value from 3 to 27 (including, 25 times in total), do it using a for loop.
It will look like this:
Hello Coddy: 3
Hello Coddy: 4
...
Hello Coddy: 27Cheat sheet
The for loop allows you to repeat code multiple times. It has the following syntax:
for (let i = start; i < end; i++) {
code;
}Where:
let i = start- sets the initial value ofii < end- condition for the loop to continuei++- incrementsiafter each iteration
Example that prints numbers 0 to 4:
for (let i = 0; i < 5; i++) {
console.log(i);
}Example summing numbers from 1 to 100:
let sum_numbers = 0;
for (let i = 1; i <= 100; i++) {
sum_numbers += i;
}
console.log(sum_numbers);Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False