Learn JavaScript_ Loops Cheatsheet _ Codecademy
Learn JavaScript_ Loops Cheatsheet _ Codecademy
Loops
Reverse Loop
A for loop can iterate “in reverse” by initializing the const items = ['apricot', 'banana',
loop variable to the starting value, testing for when the
'cherry'];
variable hits the ending value, and decrementing
(subtracting from) the loop variable at each iteration.
for (let i = items.length - 1; i >= 0; i -
= 1) {
console.log(`${i}. ${items[i]}`);
}
// Prints: 2. cherry
// Prints: 1. banana
// Prints: 0. apricot
Do…While Statement
// Prints: 0 1 3 6 10
For Loop
A for loop declares looping instructions, with three for (let i = 0; i < 4; i += 1) {
important pieces of information separated by semicolons
console.log(i);
;:
The initialization defines where to begin the loop };
by declaring (or referencing) the iterator variable
The stopping condition determines when to stop
// Output: 0, 1, 2, 3
looping (when the expression evaluates to
false )
The iteration statement updates the iterator each
time the loop is completed
An array’s length can be evaluated with the .length for (let i = 0; i < array.length; i++){
property. This is extremely helpful for looping through
console.log(array[i]);
arrays, as the .length of the array can be used as the
stopping condition in the loop. }
Break Keyword
Within a loop, the break keyword may be used to exit for (let i = 0; i < 99; i += 1) {
the loop immediately, continuing execution after the loop
if (i > 5) {
body.
Here, the break keyword is used to exit the loop when break;
i is greater than 5. }
console.log(i)
}
// Output: 0 1 2 3 4 5
Nested For Loop
A nested for loop is when a for loop runs inside for (let outer = 0; outer < 2; outer += 1)
another for loop.
{
The inner loop will run all its iterations for each iteration
of the outer loop. for (let inner = 0; inner < 3; inner +=
1) {
console.log(`${outer}-${inner}`);
}
}
/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/
Loops
The while loop creates a loop that is executed as long while (condition) {
as a specified condition evaluates to true . The loop
// code block to be executed
will continue to run until the condition evaluates to
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.
while (i < 5) {
console.log(i);
i++;
}
Print Share