DEV Community

Nedy Udombat
Nedy Udombat

Posted on • Updated on

Understanding Javascript Array Series V - Array Loops & Iteration Part II

In the previous article, I talked about iterating over arrays using For ..., For ... of & For ... in loops. You can check it out below:

In this article. I will talk about 2 other ways of iterating over an array.

1. While loop

The while loop creates an iteration that executes a specified statement as long as the specified condition evaluates to true. The specified condition is always checked before the statement is ran.


  // syntax
  while ( conditon ) {
    [statement]
  }

[condition]: This is an expression that is executed at every loop before the statement is performed. As long as the condition evaluates to true, the iteration continues, when it evaluates to false the loop breaks and the program continues with the statement after the while loop.

[statement]: This is a statement that is executed as long as the condition evaluates to true.

To loop over arrays with the while loop, the condition will be an expression of the decrement of the length of the array (e.g arrayLength--). Let's see some examples below.


   const players = ["messi", "ronaldo", "nedy", "kante"];
   let index = players.length;

   while (index--) {
     console.log(players[index]) // "kante", "nedy", "ronaldo", "messi"
   }

Doing this will result in accessing the elements of the array starting from the last element. To achieve the desired effect, one would need to:

  • Reverse the array before the while loop using the Array.prototype.reverse() method as shown below.

   const players = ["messi", "ronaldo", "nedy", "kante"];

   // reverse the array
   players.reverse();

   let index = players.length;

   while (index--) {
     console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
   }

  • Initialize a counter to -1 so that at the first run the counter would be incremented to 0, take look below

   const players = ["messi", "ronaldo", "nedy", "kante"];
   let index = -1;

   while (index++ < players.length-1) {
     console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
   }

(Thanks to @dovca for suggesting this method).

1. Do ... while loop

This method executes the statement first before checking if the condition is true until the specified condition evaluates to false.

  // syntax
  do {
    [statement]
  }
  while ( conditon )

Using a do ... while loop to iterate over an array can be tricky, because here the specified statement will run at least once before the condition is executed. Take a look at this example below


  const players = ["messi", "ronaldo", "nedy", "kante"];

  // reverse the array    0       1        2         3
  players.reverse() // "kante", "nedy", "ronaldo", "messi"

  let index = players.length;

  // itereation
  do {
    console.log(players[index]) // undefined, "messi", "ronaldo", "nedy", "kante"
  }
  while (index--)


In this scenario, we have an undefined because the statement was executed before the condition was run and as such the value for size is 4 while the array index ends at 3(players[3] = "messi"). The continue function will be used to skip the initial statement execution so that at the time it comes back around to perform the execution the value of size is 3 and we have messi logged to the console. Take a look below


  const players = ["messi", "ronaldo", "nedy", "kante"];

  // reverse the array    0       1         2         3
  players.reverse() // "kante", "nedy", "ronaldo", "messi"

  let index = players.length;

  // itereation
  do {
    // skip the initial statement
    if(index === players.length) {continue}
    console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
  }
  while (index--)

[Break] A break statement is used to stop a loop before the condition evaluates to true. As the name implies, it breaks the loop.

[Continue]: The continue statement is used to skip one iteration in a loop.

Conclusion

A lot has to be taken into consideration when using the while & do ... while loop to iterate over an array, I would advise that until the need arises one should use other iteration methods.

That's all for today, tomorrow we will talk about another set of functions used in array Iteration.

Here is the link to the other articles on this Array series written by me:

Got any question, addition or correction? Please leave a comment.

Thank you for reading. 👍

Top comments (12)

Collapse
 
rolandcsibrei profile image
Roland Csibrei • Edited

How can you use a variable name "size" for index access? This is a very bad idea. Sure, this is only a short example, however you are seeding the devil into the newcomers minds. Variable naming is crucial. Another thing is that the index variable should be initialized to size-1 when entering the while loop and should be decremented at the end for better readibility. Just my three-- cents.

Collapse
 
nedyudombat profile image
Nedy Udombat

Hi @rolandcsibrei , thank you for the correction, I appreciate it. But however what I will not appreciate is this statement however you are seeding the devil into the newcomers minds. If you want to give someone feedback make it ASK(Actionable, Specific and Kind). Thank you.

Collapse
 
rolandcsibrei profile image
Roland Csibrei

Sorry, I didn't want to be offending. I apologize.

 
nedyudombat profile image
Nedy Udombat

This has nothing to do with prefixing and suffixing the ++ an -- operators. I am saying that, when you initialize the index to 0, when the condition (index++ < players.length-1) is executed the value of index becomes 1 and the first element of the array is skipped.

Collapse
 
nedyudombat profile image
Nedy Udombat • Edited

@dovca , I see your point on calling it statements instead of functions, I will correct it to that effect.

The reason for using the .reverse() method was explained in the article, just above that section. Seeing this other approach I will, add that to the article and give due credit.

Setting the index to 1 will not work for the while loop cause at first iteration the value of index will become 1 because of the increment in the condition. However initializing index to -1 will work.

Thank you.

Collapse
 
mchardex profile image
Adebisi Oluwabukunmi

Awesome refresher. Interesting examples

Collapse
 
nedyudombat profile image
Nedy Udombat • Edited

Thank you @mchardex , I'm glad the article was of help. 👋

Collapse
 
faruq2 profile image
Faruq

Very insightful
Nice one!

Collapse
 
nedyudombat profile image
Nedy Udombat

Thank you @faruq2 . I am glad you found this useful.

Collapse
 
profjigsaw profile image
Nweze Victor Chinweudo

Awesome stuff! Keep them coming.

 
nedyudombat profile image
Nedy Udombat

Thanks for your timely corrections though, I appreciate. @dovca

Collapse
 
rolandcsibrei profile image
Roland Csibrei

It was an intention to write it that way to reflect the sample code ;-)