how to use loop 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 loop
let array = ['Item 1', 'Item 2', 'Item 3'];
for (let index = 0; index < array.length; index++) {
console.log("index", index);
console.log("array item", array[index]);
}
Example 3: javascript loops
JS Loops
for (before loop; condition for loop; execute after 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 4: javascript loop
var colors=["red","blue","green"];
for(let color of colors){
console.log(color)
}
Example 5: loops javascript
function loopy() {
while(true) {
console.log("Hello, world!");
}
}
function myFunc() {
for (let i = 1; i <= 4; i += 2) {
console.log("Still going!");
}
}