0% found this document useful (0 votes)
14 views4 pages

JavaScript Loops: For, While, Do-While

The document is a cheatsheet for JavaScript loops, explaining various types such as reverse loops, do...while statements, for loops, and while loops. It includes examples of how to implement each type of loop, along with explanations of key concepts like the break keyword and nested loops. The cheatsheet serves as a quick reference for understanding and using loops in JavaScript programming.

Uploaded by

karina wahyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

JavaScript Loops: For, While, Do-While

The document is a cheatsheet for JavaScript loops, explaining various types such as reverse loops, do...while statements, for loops, and while loops. It includes examples of how to implement each type of loop, along with explanations of key concepts like the break keyword and nested loops. The cheatsheet serves as a quick reference for understanding and using loops in JavaScript programming.

Uploaded by

karina wahyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

6/25/24, 10:19 PM Learn JavaScript: Loops Cheatsheet | Codecademy

Cheatsheets / Learn JavaScript

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 = [Link] - 1; i >= 0; i
-= 1) {
[Link](`${i}. ${items[i]}`);
}

// Prints: 2. cherry
// Prints: 1. banana
// Prints: 0. apricot

Do…While Statement

A do...while statement creates a loop that executes a x = 0


block of code once, checks if a condition is true, and
i = 0
then repeats the loop as long as the condition is true.
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;
[Link](x)
i++;
} while (i < 5);

// Prints: 0 1 3 6 10

[Link] 1/4
6/25/24, 10:19 PM Learn JavaScript: Loops Cheatsheet | Codecademy

For Loop

A for loop declares looping instructions, with three for (let i = 0; i < 4; i += 1) {
important pieces of information separated by
[Link](i);
semicolons ; :
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 )
The iteration statement updates the iterator
each time the loop is completed

Looping Through Arrays

An array’s length can be evaluated with the .length for (let i = 0; i < [Link]; i++){
property. This is extremely helpful for looping through
[Link](array[i]);
arrays, as the .length of the array can be used as the
stopping condition in the loop. }

// Output: Every item in the array

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
if (i > 5) {
loop body.
Here, the break keyword is used to exit the loop when break;
i is greater than 5. }
[Link](i)
}

// Output: 0 1 2 3 4 5

[Link] 2/4
6/25/24, 10:19 PM Learn JavaScript: Loops Cheatsheet | Codecademy

Nested For Loop

A nested for loop is when a for loop runs inside for (let outer = 0; outer < 2; outer +=
another for loop.
1) {
The inner loop will run all its iterations for each
iteration of the outer loop. for (let inner = 0; inner < 3; inner +=
1) {
[Link](`${outer}-${inner}`);
}
}

/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/

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.

[Link] 3/4
6/25/24, 10:19 PM Learn JavaScript: Loops Cheatsheet | Codecademy

While Loop

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) {
[Link](i);
i++;
}

Print Share

[Link] 4/4

Common questions

Powered by AI

Nesting loops can lead to higher computational complexity due to the multiplicative effect on iterations. This can result in significant performance degradation, especially with large data sets, as the inner loop runs entirely for each iteration of the outer loop. It can also increase the complexity of the code, making it more difficult to understand and maintain .

Both 'while' and 'do...while' loops are used for repeating a set of instructions in JavaScript, but they differ in their execution flow. A 'while' loop checks its condition before executing the block of code, and if the condition is false initially, the loop may not execute at all. Conversely, a 'do...while' loop executes the block of code once before checking the condition, ensuring that the block is executed at least once regardless of the condition .

A programmer who thoroughly understands loop constructs like for, while, and do...while can choose the most effective tool for the task, optimizing performance and code readability. Utilizing the correct loop construct ensures that code executes efficiently, managing time complexity and resource constraints effectively while minimizing logical errors and enhancing maintainability .

Stopping conditions are critical for preventing infinite loops, which can lead to unresponsive programs or systems. By ensuring a defined endpoint, stopping conditions contribute significantly to program reliability and efficiency, helping loops conclude as intended and allocate resources appropriately, which is crucial in environments with limited computational power .

A reverse for loop iterates from the last element to the first, which can be useful when removing elements from an array while avoiding index shifting issues. It is particularly advantageous in scenarios where elements at higher indices should be processed first, such as iterating over a dynamic list that shrinks, avoiding the pitfalls of index reordering after removal .

The '.length' property allows a loop to determine the exact number of elements in an array, which is useful for setting a stopping condition. This maximizes efficiency by preventing index out-of-bound errors and ensuring that every element is accessed exactly once. It simplifies the iteration process by dynamically adjusting to the array's size, which is particularly useful for arrays with a variable number of elements .

When choosing between a 'for' loop and a 'do...while' loop, it's crucial to consider the necessity of executing the loop body at least once, which favors 'do...while'. Conversely, choose a 'for' loop for more controlled iteration, especially where initialization, condition, and iteration need explicit definition upfront. The choice often depends on both the specific use case requirements and programmer preference for code readability and maintainability .

The 'break' statement is used to exit a loop immediately regardless of the inaugural loop condition. When 'break' is encountered, the execution moves to the code following the loop body. It is particularly useful in situations where a desired condition within the loop requires immediate termination of the loop, such as finding a desired element in a collection early on and avoiding unnecessary iterations .

A for loop is preferred when the number of iterations is known before entering the loop, as its structure explicitly initializes the loop variable, sets a condition, and defines the increment or decrement step, making it easier to read and maintain. In contrast, a while loop is more suited for situations where the number of iterations isn't predetermined and where the condition might depend on dynamic factors evaluated after some initial processing .

The iteration statement in a for loop updates the loop variable after each iteration, which is essential for progressing the loop towards its stopping condition, thus preventing infinite execution. Efficiently defining this update step ensures that the loop proceeds as intended, reducing processing time and preventing unnecessary complications or errors .

You might also like