adsterra

Different types of Loop in Java Script!


◼️The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
Example:

const days = ['mon','tue','wed','thr','fri','sat'] //creating array

 for (let index = 0; index <= days.length; index++) {

     const element = days[index];
      console.log(element)
     // //OR
     // console.log(days[index])
    }

// //backward loop
for (let i = 5; i >= 0; i--) {
        console.log(days[i])
     }

for (let x = 1; x<=10 ; x++) {

    console.log(2*x);  

}



◼️For-each is another array traversing technique like for loop, while loop, do-while loop in Java Script.
Example1: For Each with simple function:

const days = ['mon','tue','wed','thr','fri','sat','sun']
// console.log(days[0])
let simple =function () {  //simple is the onject of funtion
    
    console.log('hello preet')
    
}
    //this function prints 7 times hello preet as days store 7 values
days.forEach(simple

Example2:
const days = ['mon','tue','wed','thr','fri','sat','sun']
days.forEach(function (day,index){ 
 //day is its self element of string type in the array,
//2nd is the index value     
 console.log(`Start with ${index +1} ---${day}`)
 })

◼️The while and do...while statements in JavaScript are similar to Conditional Statement, which are blocks of code that will execute if a specified condition results in true. Unlike an if statement, which only evaluates once, a loop will run multiple times until the condition no longer evaluates to true.
Example:

//while

var value=5;

 while (value>0) {  
     console.log(value);
     value--;
     
}

//Do-while

do {

    console.log(value); 
    value--;

while (value>6);

Post a Comment

0 Comments