Learn JavaScript - Loops Cheatsheet - Codecademy
Learn JavaScript - Loops Cheatsheet - Codecademy
Loops
Reverse Loop
A for loop can iterate “in reverse” by initializing the
loop variable to the starting value, testing for when the const items = ['apricot', 'banana',
variable hits the ending value, and decrementing 'cherry'];
(subtracting from) the loop variable at each iteration.
// Prints: 2. cherry
// Prints: 1. banana
// Prints: 0. apricot
/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/
While Loop
The while loop creates a loop that is executed as long
as a specified condition evaluates to true . The loop while (condition) {
will continue to run until the condition evaluates to // code block to be executed
false . The condition is specified before the loop, and }
usually, some variable is incremented or altered in the
while loop body to determine when the loop should
let i = 0;
stop.
Do…While Statement
A do...while statement creates a loop that executes a
block of code once, checks if a condition is true, and x = 0
then repeats the loop as long as the condition is true. i = 0
They are used when you want the code to always
execute at least once. The loop ends when the
do {
condition evaluates to false.
x = x + i;
console.log(x)
i++;
} while (i < 5);
Break Keyword
Within a loop, the break keyword may be used to exit
the loop immediately, continuing execution after the for (let i = 0; i < 99; i += 1) {
loop body. if (i > 5) {
Here, the break keyword is used to exit the loop when break;
i is greater than 5.
}
console.log(i)
}
Loops
A loop is a programming tool that is used to repeat a set
of instructions. Iterate is a generic term that means “to
repeat” in the context of loops. A loop will continue to
iterate until a specified condition, commonly known as
a stopping condition, is met.
For Loop
A for loop declares looping instructions, with three
important pieces of information separated by for (let i = 0; i < 4; i += 1) {
semicolons ; : console.log(i);
};
The initialization defines where to begin the loop
by declaring (or referencing) the iterator variable
// Output: 0, 1, 2, 3
The stopping condition determines when to stop
looping (when the expression evaluates to
false )