looping for 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 loop
let array = ['Item 1', 'Item 2', 'Item 3'];
for (let index = 0; index < array.length; index++) {
console.log(array[index]);
}
for (let index in array) {
console.log(array[index]);
}
for (let value of array) {
console.log(value);
}
array.forEach((value, index) => {
console.log(index);
console.log(value);
});
Example 3: for in loop javascript
function diagonalDifference(arr) {
let n = arr.length;
let pri,sec = 0;
pri = sec = 0;
for (let i= 0; i < n; i++) {
pri += arr[i][i];
sec += arr[i][n - i - 1];
}
if(pri==sec){
return (0);
}else {
if (pri>sec){
return (pri-sec);
}else{
return (sec-pri);
}
}
}