Loops in JavaScript || Client Side Scripting || BCIS Notes

Loops in JavaScript || Client Side Scripting || BCIS Notes

Loops in JavaScript

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort. JavaScript now supports five different types of loops:

  1. while — loops through a block of code as long as the condition specified evaluates to true.
  2. do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
  3. for — loops through a block of code until the counter reaches a specified number.
  4. for…in — loops through the properties of an object.
  5. for…of — loops over iterable objects such as arrays, strings, etc.

The while Loop

This is the simplest looping statement provided by JavaScript.

The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

while(condition) {
// Code to be executed

}

The while Loop

The do…while Loop

The do-while loop is a variant of the loop, which evaluates the condition at the end of each loop iteration. With a do-while loop, the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is:

do {
// Code to be executed

} while(condition);

The do...while Loop

The for Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code a certain number of times. Its syntax is:

for(initialization; condition; increment) {

// Code to be executed

}

The for Loop

The for loop is particularly useful for iterating over an array.

The for Loop

The for…in Loop

The for-in loop is a special type of loop that iterates over the properties of an object, or the elements of an array. The generic syntax of the for-in loop is:

for(variable in object) {

// Code to be executed

}

The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of the current property or the index of the current array element.

The for...in Loop

The for…of Loop ES6

ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

The for...of Loop

If you liked our content Loops in JavaScript, then you will also like JavaScript Arrays

Be the first to comment

Leave a Reply

Your email address will not be published.


*