JavaScript provides repeating code with control is provided in the form of loops..
- for
- for…in
- forEach
- while
- do…while
for(initialization; condition; increment) {
// Code to be executed
// eg. for loop
for(var i=1; i<=5; i++) {
console.log(i);
}
// output: 1 2 3 4 5
}
initialization:- It is used to initialize the counter variables, for example, let i=0.
Condition:- The condition is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute, and If it evaluates to false, the execution of the loop ends, i.e., i < 100.
Increment:- it updates the loop counter with an incremented value value each time the loop runs for example i++;
2. for… in Loop
used when we want to iterates over the properties of an object or the elements of an array.
for(variable in object) {
// Code to be executed
}
// eg. for... in loop
// An object with some properties
var person = {name: "Pradeep", language: "JavaScript"};
// Loop through all the properties in the object
for(var i in person) {
console.log( i + " = " + person[i]);
}
// Output: name = pradeep language = JavaScript
3.forEach Loop
forEach is a type of loop that is used for Array method. With the help of forEach loop, we can execute a function on each item within an array. The function can only be used on Arrays.
const alphabates = ['a', 'b', 'c'];
alphabates.forEach((element)=>{
console.log(element);
})
// Output: name = a b c
4. while loop
used when we do not know how many times a certain block of code should execute. It evaluates the expression inside the parenthesis (). If the expression evaluates to true, the code inside the while loop is executed. Every time the expression is re-evaluated, the process continues until the expression evaluates to false. When the expression evaluates to false, the loop stops.
while (expression) {
// body of loop
}
// eg.
let i = 1, n = 10;
while (i <= n) {
console.log(i);
i += 1;
}
// Output: name = 1 2 3 4 5 6 7 8 9 10
Comments
Post a Comment