Loop (for & a while) in JavaScript

Loop (for & a while) in JavaScript

Ā·

7 min read

Welcome to my other blog on JavaScript and in this blog we are going to see for & while Loops in JS.

Let's get started šŸš€

lets-get-into-it-nik-nocturnal.gif (400Ɨ344)

Loops

In programming, we need to perform operations and actions that need to be performed repeated times and that's where... Loops came in to picture.

For Example:

Send "How are you?" message to 10 person.

while loop

while a loop is a type of loop that contains 3 components- initiation, condition, and iterator.
Let's talk about them one by one.

Initialize

let i = 1;

Here, we have initialized the value of i as 1;

Condition

while( .... ){
// statement
}

Here we have put conditions depending on which code statements will execute or not.

Iterator

i++;

In this last type, we are incrementing the value of i by 1,

let i = 0;
while (i < 2) { // shows 0, then 1
  alert( i );
  i++;
}

A single execution of the loop body is called an iteration. The loop in the example above makes three iterations.

If i++ was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.

Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by while.

āš ļø Curly braces are not required for a single-line body {}

let i = 5;
while (i) alert(i--);

do-while loop

In this type of loop, the condition is checked below the statement.

Syntax

do {
  // statement 
} while (condition);

The loop will first execute the statement, then check the condition, and while itā€™s true, execute it again and again.

For example:

let i = 1;
do {
  alert( i );
  i++;
} while (i < 0);

Output:

1

for loop

The for loop is the most commonly used loop, the basics of this loop are similar to while loop.

Syntax:

for (initailize; condition; iterator) {
  // ... loop body ...
}

Let's understand this:

for(let i = 0; i < 4; i++){ 
  alert(i);
}
Initialize
we start with i=0

Now check condition

Condition
i=0 is less than 4

so, now execute the statement in the code block,
show alert(0).

After executing this step,

Now, move towards iterator part,

Iterator
i++

now, for the next step. Value of I would be 1.

Similarly when i=4, code will stop working!

Letā€™s understand the for statement part-wise:

part
beginlet i = 0Executes once upon entering the loop.
conditioni < 4Checked before every loop iteration. If false, the loop stops.
bodyalert(i)Runs again and again while the condition is truthy.
stepi++Executes after the body on each iteration.

More clear:

// for (let i = 0; i < 3; i++) alert(i)

// run begin
let i = 0
// if condition ā†’ run body and run step
if (i < 4) { alert(i); i++ }
// if condition ā†’ run body and run step
if (i < 4) { alert(i); i++ }
// if condition ā†’ run body and run step
if (i < 4) { alert(i); i++ }
// if condition ā†’ run body and run step
if (i < 4) { alert(i); i++ }
// Finish

Skipping parts

This is another topic and it is all about skipping some parts of for loop.
Let's understand!

for can be skipped at any point.

If there is nothing to be done at the start of the loop, for instance, we can omit the word begin.

let i = 0; 

for (; i < 4; i++) { 
  alert( i );
}

We can also skip the iterator part:

let i = 0;

for (; i < 4;) {
  alert( i++ );
}

This makes the loop identical to while (i < 4).

We can actually remove everything, creating an infinite loop:

for (;;) {
  // repeat without condition
}

break

Usually, we see a loop run until the condition is satisfied, but we can exit at any time by using the break directive.

let sum = 0;

while (true) {

  let value = +prompt("Enter a number", '');

  if (!value) break;

  sum += value;

}
alert( 'Sum: ' + sum );

break the directive is activated at the line (*) if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, alert.

Continue

It works similarly to break that we have covered previously,
We can use it if weā€™re done with the current iteration and would like to move on to the next one.
The loop below uses continue to output only odd values:

for (let i = 0; i < 10; i++) {

  if (i % 2 == 0) continue;
  alert(i); // 1, then 3, 5, 7, 9
}

No break/continue to the right side of ā€˜?ā€™

Please note that syntax constructs that are not expressions cannot be used with the ternary operator ?. In particular, directives such as break/continue arenā€™t allowed there.

For example, if we take this code:

if (i > 5) {
  alert(i);
} else {
  continue;
}
(i > 5) ? alert(i) : continue;

Labels for break/continue

Sometimes we need to break out from multiple nested loops at once.

For example, in the code below we loop over i and j, prompting for the coordinates (i, j) from (0,0) to (2,2):

for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 3; j++) {

    let input = prompt(`Value at coords (${i},${j})`, '');

    // what if we want to exit from here to Done (below)?
  }
}

alert('Done!');

We need a way to stop the process if the user cancels the input.

The ordinary break after input would only break the inner loop. Thatā€™s not sufficient ā€“ labels, come to the rescue!

A label is an identifier with a colon before a loop:

labelName: for (...) {
  ...
}

The break <labelName> statement in the loop below breaks out to the label:

outer: for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 3; j++) {

    let input = prompt(`Value at coords (${i},${j})`, '');

    // if an empty string or canceled, then break out of both loops
    if (!input) break outer; // (*)

    // do something with the value...
  }
}

alert('Done!');

In the code above, break outer looks upwards for the label named outer and breaks out of that loop.

So the control goes straight from (*) to alert('Done!').

We can also move the label onto a separate line:

outer:
for (let i = 0; i < 3; i++) { ... }

The continue directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop.

Labels do not allow to ā€œjumpā€ anywhere

Labels do not allow us to jump into an arbitrary place in the code.

For example, it is impossible to do this:

break label; // jump to the label below (doesn't work)

label: for (...)

A break directive must be inside a code block. Technically, any labelled code block will do, e.g.:

label: {
  // ...
  break label; // works
  // ...
}

ā€¦Although, 99.9% of the time break is used inside loops, as weā€™ve seen in the examples above.

A continue is only possible from inside a loop.

Hope you loved this blog

Don't forget to like and follow this blogāœØ

See you soon..
Have a good day my friendšŸ„°

Ā