Loops in Javascript
- for loop
- Execute code a certain amount of times (with counter variable)
- for-of loop
- Execute for every element in an
array
- Execute for every element in an
- for-in loop
- Execute for every key in an
object
- Execute for every key in an
- while loop
- Execute code as long as a condition is true
Loop control
- continue
- skip the current iteration
- break
- terminates the loop
labeled statement
- The labeled statement can be used with
break or continue statements
. - It is prefixing a statement with an identifier which you can refer to.
- The labeled statement can be used with
loop1:
for (i = 0; i < 3; i++) {
loop2:
for (j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break loop1;
// break both inner and outer loop
}
console.log('i = ' + i + ', j = ' + j);
}
}
Page: /
FOR LOOP
// let i, not const
for(let i = 0; i < 10; i++){
if(i === 2){
console.log('2 is my favorite number');
continue; // skip the current iteration
}
if(i === 5){
console.log('Stop the loop');
break; // terminates the loop
}
console.log('For loop '+ i);
}
FOR-OF LOOP
- for-of –>
iterates over values
- Loop through
array but not object
- Can’t access index
var arr = ['a','b','c','d']
arr.ap = "x"
// const i,
for(const i of arr){
console.log(i) // a b c d
}
console.log(arr)
FOR-IN LOOP
- for-in –>
iterates over properties
- used for iterating over
enumerable properties
ofobjects
- Loop through
array and Object
const cars = ['Ford', 'Chevy'];
for(let i = 0; i < cars.length; i++){
console.log(cars[i]);
}
for(i in cars){
console.log(i, cars[i])
}
FOR-OF can't be used in object
var hash = {
'a1': "Apple",
'b1': "Mango"
}
for(i in hash){
console.log(i, ": ", hash[i])
}
// ERROR
// for(i of hash){
// console.log(i)
// }
for-of vs for-in
to access array
let array = []
array[4] = '4th'
array[5] = '5th'
console.log(array)
// [undefined, undefined, undefined, undefined, "4th", "5th"]
for (let i in array) {
console.log(i,": " ,array[i])
}
// 4: 4th, 5: 5th
for (let i of array) {
console.log(i)
}
// [undefined, undefined, undefined, undefined, "4th", "5th"]
WHILE LOOP
// WHILE LOOP
i = 0;
while(i < 3){
console.log('While ' + i);
i++;
}
// DO WHILE
i = 0;
do {
console.log('Do while ' + i);
i++;
}while(i < 3);
FOREACH LOOP
- The arr.forEach method allows to run a function for every element of the array.
cars.forEach(function(car){
console.log(car);
});
cars.forEach(function(car, index, array){
console.log(`${index} : ${car}`); //or
// console.log(index,' : ',car);
console.log(array[index]);
});
people = ["Bilbo", "Gandalf", "Nazgul"]
people.forEach(console.log); // 3-times
people.forEach(function(i){
console.log(i)
});