Loops and iterations in JavaScript

Loops and iterations in JavaScript

Standard loops

loop

There is often a need to execute some lines of code multiple times within a program. This mode of execution is achieved by means of appropriate management structures. Loops and iterations are the basic building block of any program. Standard loops occur in more or less the same form in almost all programming languages. The most used is “for loop”. Special attention should be paid to while loops because there is a possibility that the loop may become infinite due to a bad choice of conditions.

“while” loop

The while statement is executed as long as the condition is TRUE, and if it is not then the loop is exited. This type of loop is most often used when the exact number of elevations of the loop is not known. In case the condition is not met at the very beginning, the loop is not executed once. Before entering the loop, variables are initialized that will be used either in the condition or in the body of the loop. The body of the loop contains the code that forms the condition for remaining in the loop.

This type is called a “pre-test loop” because the condition is executed before the expression block.

The expression “n++” is called “updater”. Most often, the initial values ​​for the condition are defined before the loop. Pay attention to the possibility of creating an “infinite loop” if there is no updater.

do..while loop

The statement in the do…while loop is executed until the condition is FALSE. The difference between “do…while” and “while” loops is that here the expression is executed at least once, while with “while” there is a possibility that the expression is never executed if the condition at the start is FALSE.

This type of loop is most often used when an expression in the body of the loop generates a value to be used in a condition.

“for” loop

This is the most commonly used loop. Unlike “while” and “do…while” loops where the key loop points [initial value], [condition] and [increment expression] are in different places, here a structure called “iteration statement” keeps them together, on one line, separated by semicolons.

This type of loop is used if at the beginning the exact number of loop executions is known.

Additional commands

break

The break statement is used to break out of the body of the loop. It is located somewhere in the body of the loop, usually after some additional condition. Can be used with any loop type mentioned.

BREAK in FOR loop

The result is:

continue

With the continue command, the execution of iterations is not interrupted, but the current iteration is skipped.

continue in FOR loop

The result is:

continue in WHILE loop

Result:

Loop labels

Loop labels is a syntax that enables the labeling of loops. A label (loop name) is placed before each loop along with a colon.

Marking loops gives us the possibility that when using the break or continue commands, we can select the loop to which we want to apply the commands.

Iteration through arrays forEach()

This method executes a specific function (callback) using each element of the passed array. This function is less flexible than the standard “for loop” because it has no conditional statements and there is no way to terminate a “loop” once started other than throwing an exception. The method passes three parameters to the callback function:

  • string member value
  • index of array member
  • an array (on which the method is executed)

In addition to the callback function, the argument thisArg can (optionally) be passed, which defines what the reserved word this will point to within the callback function. The function itself does not automatically return anything, so it is not “chainable” (the next method cannot be chained to it). Even after explicitly using the return statement, it will not return anything after the iteration.

Example

The same result can be obtained using other attributes

Example

Callback function cannot use “empty array members” (array member with an index that has no associated value) in the calculation. Therefore, in the following example, this method will not take into account an empty element, so the array member with index 2 will be skipped:

Iteration through the object for..in

This is a specific “for” loop that passes through all the properties of an object where the property descriptor is enumerable, set to TRUE. This method can also be applied to arrays, but it has limitations and a lot of unwanted side effects, so it is recommended to use some other method to iterate through arrays (eg “for…of” loop).

NOTE:
It should be emphasized that with this method of iteration, the order of the members of the iteration is not guaranteed.

The result is:

NOTE: The
for…in loop “passes through” even properties that are inherited through the parent’s prototype object.

This loop will return the properties of the dragoljub object (Dragoljub, javascript) but also the inherited property from the parent (programmer). If we still want to return only the “personal” properties of the object, we have to filter using the hasOwnProperty method, as in the following example:

This code returns only the personal properties of the “dragoljub” object: Dragoljub and javascript.

NOTE:
“for..in” loop goes through all properties of the object, and even through those that inherit through the chain of inheritance, so if we are interested only in the “personal” properties of the object, there is a possibility of transforming the object into a string. One of the following methods is used for this: Object.values(obj), Object.keys(obj) or Object.entries(obj). Read more about these methods in the article “Object() & Object.prototype”

Iteration through iterable for..of

This is a new way of iteration that came bundled with the ES6 standard. Iterating with “for…of” goes through the values ​​of the iterable collection. It is used for all iterable collections (Array, Map, Set, String…), but it is not planned to iterate through object properties.

where is:

  • Member value – represents a new value assigned at each iteration
  • collection – the name of the collection whose properties are iterated through

Unlike for…in where the constant order of iteration is not guaranteed, with this method iterations are performed according to the order.

Result:

Iteration through the “array”

Iterations through “string”

Iterations through the DOM

Iterations through MAP

Iteration through Set

Iteration through generators

Iteration through the object
NOTE:
Although this iteration method is not intended for object iteration, there is a workaround to apply it to objects as well using Object.keys():