Different iteration statements in javascript
1) for loop for loop will repeat until a specified condition met.
for([initialExpression],[conditionExpression],[incrementExpression])
example
const arr = [10,20,25,55,60,80,95];
let count = 0;
for(let i=0; i < arr.length; i++){
if(arr[i] % 10 === 0){
count++;
}
}
console.log(count) // 4
here for loop runs until the i
value becomes more than the length of an array.
2) for...in
for-in
is used to iterate over the properties of objectfor-in
loop iterates only over those keys of an object which have their enumerable property set to “true”- order of execution and properties defined in the object will not be the same.
const obj= {firstname:"Elon", lastname:"Musk", age:50, company:"Tesla"};
let ans = ""
for (let key in obj) {
ans += obj[key] + " ";
}
console.log(ans) // Elon Musk 50 Tesla
- we can use
for..in
with an array but if an order of index matters then don't use it. in this case usefor loop
,forEach
,for..of
3) for...of
for..of
will iterate over property value
for..in
will iterate over the property name
const arr = ['apple', 'orange', 'mango', 'banana']
let ans = "";
for(let i of arr) {
ans += i + " "
}
console.log(ans) // apple orange mango banana
also, iterate over the string
const string = "Javascript"
let ans = "";
for(let i of string) {
ans += i + " "
}
console.log(ans) // J a v a s c r i p t
4) while loop
while
loop through a block of code as long as specified conditions are true.
once the condition becomes false
it will stop execution and control passes to next statement
const x = 10
white(i < x){
console.log(i);
i++;
}
// 1 2 3 4 5 6 7 8 9
if the condition does not become false then it goes into an infinite execution
while(true){
console.log("Infine loop")
}
5) do...while loop
do...while
works the same as while just it executes once before it checks the condition.
const x = 5
let i = 0;
do {
console.log(i);
i++;
}while(i <= x)
// 0 1 2 3 4 5