The for loop is the most basic type of loop and is used to iterate through an array, object, or other data structure. It is the most efficient way to loop through data and is used most often when working with arrays.
The syntax for a for loop is as follows:
for (let i = 0; i < arr.length; i++) {
// code to execute
}
The initialization is the first step of the loop, and it sets the initial value of the loop counter. The condition is evaluated at the beginning of each loop iteration. If the condition evaluates to true, the code block is executed and the loop counter is incremented or decremented. If the condition evaluates to false, the loop is terminated.
For example, the following code will print the numbers from 1 to 10:
for (var i = 1; i <= 10; i++) {
console.log(i);
}
The for loop is an extremely powerful construct, and it can be used for a variety of purposes. It is commonly used to iterate through an array or an object, but it can also be used to execute a particular set of instructions a certain number of times.
Let’s iterrate the charactors of a string
var str = "hello";
var res = "";
for (var i = 0; i < str.length; i++) {
res += str[i] + "\n";
}
console.log(res);
/*
Output
h
e
l
l
o
*/
Example to iterate the items of array
var arr = ["a", "b", "c", "d"];
var res = "";
for (var i = 0; i < arr.length; i++) {
res += arr[i] + " ";
}
console.log(res); // a b c d
You can compare the all the options to iterate the array
Example to iterate the object
var obj = {
a: "a",
b: "b",
c: "c",
d: "d"
};
var res = "";
for (var i in obj) {
res += obj[i] + " ";
}
console.log(res);
Leave a Reply