creating loops in javascript code example

Example 1: javascript for loop

var colors=["red","blue","green"];
for (let i = 0; i < colors.length; i++) { 
  console.log(colors[i]);
}

Example 2: javascript loops

JS Loops
for (before loop; condition for loop; execute after loop) {
// what to do during the loop
}
for
The most common way to create a loop in Javascript
while
Sets up conditions under which a loop executes
do while
Similar to the while loop, however, it executes at least once and performs a check at the end to
see if the condition is met to execute again
break
Used to stop and exit the cycle at certain conditions
continue
Skip parts of the cycle if certain conditions are met

Example 3: for in loop javascript

function diagonalDifference(arr) {
    // Write your code here
    // return (arr); 11,2,4,4,5,6,10,8,-12
    let n = arr.length;
    let pri,sec = 0;

    pri = sec = 0; //initialize both diagonal sum to 0
    for (let i= 0; i < n; i++) {
        //console.log( "PRI(arr)= ", i,i);
        //console.log( arr[i][i]);
        //console.log( "SEC(arr)= ", i,n-i-1);
        //console.log( arr[i][n-i-1]);
        pri += arr[i][i];
        sec += arr[i][n - i - 1]; 
    }
	
  	// return |x| is the absolute value of x
    if(pri==sec){
        return (0);
    }else {
        if (pri>sec){
            return (pri-sec);
        }else{
            return (sec-pri);
        }
    }
}

Example 4: loops javascript

/*Loops are great tools when you need your program to run a code block a 
certain number of times or until a condition is met, but they need a 
terminal condition that ends the looping. Infinite loops are likely to 
freeze or crash the browser, and cause general program execution mayhem, 
which no one wants.

Infinite loop example(do not call this function!):*/
function loopy() {
  while(true) {
    console.log("Hello, world!");
  }
}

/*Loop example with terminal condition:*/
function myFunc() {
  for (let i = 1; i <= 4; i += 2) {
    console.log("Still going!");
  }
}

Tags:

Cpp Example