6. Loops and Iterations in Javascript
for loop
The
for
loop is commonly used when the number of iterations is known.
for (let i = 0; i < 5; i++) {
console.log(i);
}
while loop
The
while
loop executes as long as the specified condition istrue
.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do while loop
The
do...while
loop ensures that the loop body executes at least once, even if the condition is false.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
for...in
LoopThe
for...in
loop iterates over the properties of an object.
let object ={
name:"Ayush",
lastName:"Rajput",
age: 21,
}
for(let key in object){
console.log(key + "->" + object[key])
}
/* Output
name->Ayush
lastname->Rajput
age:21
*/
In JS arrays are nothing they are objects so we also iterate over array using for..in loop
let arr = [ 1,2,3,4]
arr.myprop = "Hello"
console.log(arr);
for(let key in arr){
console.log(key + "->" + arr[key]); // here key is array indexs
}
/* Output
[ 1, 2, 3, 4, myprop: 'Hello' ]
0->1
1->2
2->3
3->4
myprop->Hello
*/
for...of
LoopThe
for...of
loop is used for iterating over iterable objects like arrays, strings, maps, sets, etc.
const arr = [10, 20, 30];
for (let value of arr) {
console.log(num);
}
/*output
10
20
30
Break and Continue
The
break
statement terminates the loop immediately.The
continue
statement skips the current iteration and moves to the next one.
Interview Questions
// what will be the output for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } /* 3 3 3
Explanation: Since
var
is function-scoped, the loop completes first, settingi = 3
, and only then do thesetTimeout
functions execute, all printing3
.If we use let in place of var then output will be : 0, 1,2
Since
let
is block-scoped, a newi
is created for each loop iteration.What is the difference between
for...in
andfor...of
?
for..in | for..of | |
Iterate over | Keys of an object or array | Values of an iterable |
Suitable for | Objects | Arrays, strings, maps, sets |
Example | for (let key in obj) {} | for (let value of arr) {} |
What is infinite loop ? Give example .
A loop that never ends due to a missing exit condition.
while (true) { console.log("Infinite loop"); }