Iterative Control

 While loop


// While Loop
let x = 5;
while (x) {


    console.log(x);
    x --;
}

// do while Loop

let y = 10;
do {
   
    console.log(y);
    y--;
} while (y);


for Loop

array = [1,2,3,4,5]
for (let index = 0; index < array.length; index++) {
    if (array[index] %2 == 0)
    {
        const element = array[index];
    console.log(element);

    }
       
}


for in loop 

This loop is used to access elements of an object. 

//  for in loop

person = {

    name: 'hari',
    age:'25'
};
for (const key in person) {
     
    console.log(key,person[key]);
}

Similarly, we can iterate object such as array. In case of array key is 0,1,2... and value can be accessed as below.

//  for in loop

arr = [10,20,30,40,50]
for (const key in arr) {
     
    console.log(key,arr[key]);
}

Output 

0 10

1 20

2 30

3 40

4 50


for of loop 

This loop works similar to for loop in Python and foreach loop in Java

cars = ["Tesla",4,6,"Mercedes"]
for (const car of cars) {
    console.log(car)
}

Transfer statements 

break,continue,return - Same as C language

break - it is used in body of loop or switch

continue - bypass current execution

return - to return value via function 




Comments