for Loop
The for loop is used to execute a block of code a given number of times, which is specified by a condition.
Example
for (let i = 0; i < 3; i++) {
console.log ("Serial Number" + i);
}
Output
Serial Number0
Serial Number1
Serial Number2
for...of Loop:
This will be used with arrays,lists,tuples
Example
for (let i = 0; i < 3; i++) {
console.log ("Serial Number" + i);
}
let arr = [10, 20, 30, 40];
for (var val of arr) {
console.log(val);
}
Output
Serial Number0
Serial Number1
Serial Number2
10
20
30
40
for...in Loop
This can be used with an array, list, or tuple. The for...in loop iterates through a list or collection and returns an index on each iteration.
for (let i = 0; i < 3; i++) {
console.log ("Serial Number" + i);
}
let arr = [10, 20, 30, 40];
for (var val of arr) {
console.log(val);
}
for (var index in arr) {
console.log(index);
console.log(arr[index]);
}
Output
10
20
30
40
0
10
1
20
2
30
3
40
While Loop
The loop runs until the condition value is met.
Example
let i: number = 2;
while (i < 4) {
console.log( "Serial Number." + i )
i++;
}
Output
Serial Number.2
Serial Number.3
do..while loop
The do..while loop is similar to the while loop, except that the condition is given at the end of the loop. The do..while loop runs the block of code at least once before checking for the specified condition. For the rest of the iterations, it runs the block of code only if the specified condition is met.
Example
Syntax:
do {
// code block to be executed
}
while (condition expression);
let i: number = 2;do {console.log("Serial Number." + i )i++;} while ( i < 4)
Output
Serial Number.2
Serial Number.3
No comments:
Post a Comment
Thank you for visiting my blog