javascript

Loops

It's often important to have something happen multiple times in programming. For example, if a user submits a form with multiple fields, you could get all of the fields into an array or an object, and then iterate over them, doing something with each field (validating it, formatting it, etc).


There are five ways to loop in javascript:

  1. while (run a piece of code x times while a condition is true)
  2. do...while (the same as while, but run the code before checking the condition)
  3. for (a type of loop that uses an iterator (an increasing/decreasing number), a condition (x < 10 or etc.), and an iterator change (x +1 or x - 1)
  4. for ... in (a type of loop that iterates over an object or array)
  5. for ... of (a type of loop that iterates over an object or array)


The first three types of loops use conditions to tell when they should stop happening. If the condition is incorrect, it can lead to an infinite loop, which in Javascript, can crash a web page.


The last two can be useful if you already have an object or array you want to loop over. These shouldn't lead to infinite loops since they loop over variables of limited size.


The following pseudocode (code which isn't valid runnable code, but is used to demonstrate an idea) provides examples of each loop type:


  1. for loop: This loop is used to execute a block of code a specific number of times. The syntax of a for loop is as follows:
for (initialization; condition; increment/decrement) { // code to be executed } 

Here, initialization sets the starting point of the loop, condition specifies when the loop should end, and increment/decrement updates the loop variable on each iteration.


  1. while loop: This loop is used to execute a block of code while a specific condition is true. The syntax of a while loop is as follows:
while (condition) { // code to be executed } 

Here, condition is the condition that is checked before each iteration.


  1. do-while loop: This loop is similar to the while loop, but it executes the block of code at least once before checking the condition. The syntax of a do-while loop is as follows:
do { // code to be executed } while (condition); 

Here, the block of code is executed once before checking the condition.


  1. for...in loop: This loop is used to iterate over the properties of an object. The syntax of a for...in loop is as follows:
for (let key in object) { // code to be executed } 

Here, key is the name of each property in the object.


  1. for...of loop: This loop is used to iterate over the values of an iterable object such as an array or a string. The syntax of a for...of loop is as follows:
for (let value of iterable) { // code to be executed } 

Here, value is the value of each element in the iterable object.