javascript

Loops in Javascript are the typical ones we find in languages ​​like Java or C, with some of Javascript’s own to perform visits to structures such as arrays, objects or iterables.

These are the most elementary loops that the language gives us:

for-loop

The for loop is the lowest level iteration structure, which requires us to supply the concrete values ​​of initialization, repeat condition, and increment between iterations.

for(var i = 0; i < 10; i++) { alert(i); }

while-loop

The while loop is executed whenever a condition expressed in the loop header is met. The initialization of the loop and the increment at each iteration are not explicitly expressed.

var i = 0; while(i < 10) { alert(i); i++; }

do … while loop

The do while loop is similar in structure to the while loop, except that the condition is performed at the end of the repeat block. Therefore, this loop will always be executed at least once.

var i = 0; do { alert(i); i++ } while(i < 10)

We also have other Javascript-specific loops such as for in or forEach, which help us to comfortably go through structures, whether they are object properties or array cells.

loop for … in

It allows to obtain the indices of a structure in each iteration. For example, if we use it to loop through an object, we’ll get the name of the current property and iterate through the number of existing properties on the object.

var website = { name: ‘WebDevelopment’, theme: ‘Development, design, programming’, } for(var property in website) { alert(property + “https://webdevelopment.com/” + website); }

loop for … of

This loop works in much the same way as for … in, but instead of giving you the index of the structure you are traversing, it gives you the value. However, it cannot be used with objects, but with arrays or iterables.

See also  Main features of OsCommerce

var numbers = ; for(var current of numbers) { alert(current); }

forEach Loop

We could refer to it as an alternative to loop, but it’s actually a method of certain structures like arrays. We feed this method with a function sent by parameter, which will be executed as many times as there are elements in the array.

var numbers = ; numbers.forEach( current => alert(current));

That anonymous function receives a parameter that will have the value of the current element of the iteration. We can also define a second parameter that would have the value of the current index of the array and a third parameter that would be the array that we are traversing.

Loading Facebook Comments ...
Loading Disqus Comments ...