For and While Loops in JavaScript
What are loops?
In computer science loops are control flow statements used for conveying iteration. Particularly, loops are used to execute a block of code repeatedly until a certain condition is met. Loops are exceptionally useful for accomplishing tasks that need to be performed multiple times. This saves time by preventing writing the same code over and over. JavaScript has two main types of loops, for loops and while loops.
For loops
Executes a block of code a specified number of times.
for:
The reserved word 'for' creates a loop that takes 3 optional expressions:
The first expression (Initialization) is executed one time before the execution of the code block. e.g. (let i = 0;)
The second expression (conditional) defines the condition for executing the code block. e.g. (i < 5;)
The third expression (Incrementor )is executed every time after the code block has been executed. e.g. (i++)
In the image below, the for loop will iterate over the code block incrementing the 'i' variable until 'i' is no longer less than 5.
for...of:
Used to iterate over elements of an iterable object (like arrays or strings).
for...in:
Used to iterate over an object's properties.
While loops
Executes a block of code as long as the designated condition is true.
while:
Executes the block of code until the condition becomes false.
do-while:
Works similarly to the while loop but, the block of code is executed at least once before the condition is checked.
Summary
Loops are fundamental concepts in computer science and programming. They are used to iterate certain actions multiple times and control the flow of execution in programs. The main types of loops in JavaScript are for loops and while loops.
References
MozDevNet. (n.d.). For - javascript: MDN. JavaScript | MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
JavaScript for loop. JavaScript for Loop. (n.d.). https://www.w3schools.com/js/js_loop_for.asp
JavaScript while loop. JavaScript while Loop. (n.d.). https://www.w3schools.com/js/js_loop_while.asp
GeeksforGeeks. (2023, May 19). Loops in JavaScript. GeeksforGeeks. https://www.geeksforgeeks.org/loops-in-javascript/