loop
Estimated reading time: 4 minuteswhat is loop
loop is a reapeting process in same block (excute over and over in same block)
loop type
- while
- do – while
- for
- forEach
- for … in
- for … of
while
while(yourCondition) {
statement
increment/decrement
}
let num = 1;
while (num < 10) {
console.log(num);
num++;
}
do while
do () {
Statements,
inc/dec
} while (yourCondition);
let num = 1;
do {
console.log(num);
num++;
} while (num < 10);
// output: 1,2,3,4,5,6,7,8,9
- do statement return first then other task
let num = 11;
do {
console.log(num);
num++;
} while (num < 10);
// output: 11
for
for (initialization; condition; inc/dec) {
statement;
}
for (let num = 1; num < 10; num++) {
console.log(num);
}
// output: 1,2,3,4,5,6,7,8,9
let nums = [];
for (let i = 0 ; i < 10 ; i++) {
nums.push(i);
}
nums.forEach(t => console.log(t));
// 1,2,3,4,5,6,7,8,9
break
- loop stop (if fullfill condition)
for (let num = 1; num < 10; num++) {
if(num == 5) {
break;
}
console.log(num);
}
// output: 1,2,3,4
continue
- skip (not condition fullfill)
for (let num = 1; num < 10; num++) {
if(num % 2 != 0) {
continue;
}
console.log(num);
}
// output:
// 2,4,6,8,10
for…in
- for…in return array index
let users = ['kamal','jamal','maruf','sadia','kalam','karim'];
for (user in users) {
console.log(user);
}
//output
// 0
// 1
// 2
// 3
// 4
// 5
for…of
- return array value
let users = ['kamal','jamal','maruf','sadia','kalam','karim'];
for (user of users) {
console.log(user);
}
// output
// kamal
// jamal
// maruf
// sadia
// kalam
// karim
forEach
let users = ['kamal','jamal','maruf','sadia','kalam','karim'];
users.forEach ((name,index) => {
console.log(index +' user name '+ 'is' + ' ' + name);
})
// output:
// 0 user name is kamal
// 1 user name is jamal
// 2 user name is maruf
// 3 user name is sadia
// 4 user name is kalam
// 5 user name is karim