LOOPS
Loops in Js
Loops are used to repeatedly execute a block of code until a certain condition is met.
JavaScript provides several ways to iterate through an array, including the for loop, forEach method, and for...of loop.
For loop
This is the most basic way to iterate through an array. The for loop uses a counter variable that is incremented on each iteration.
The for loop is used when you know in advance how many times you want to iterate.
1for (let i = 0; i < 5; i++) {
2 console.log(i);
3 // 0 1 2 3 4
4}
5
For-in loop
The for-in loop is used to iterate over the properties of an object. It has the following syntax:
1for (variable in object) {
2 // code to be executed
3}
The variable is assigned the name of each property in the object as the loop iterates over them.
Here's an example of a for-in loop that iterates over the properties of an object:
1let person = {
2 name: "John",
3 age: 30,
4 job: "developer"
5};
6
7for (let key in person) {
8 console.log(key + ": " + person[key]);
9}
This loop will print the following to the console:
1name: John
2age: 30
3job: developer
For-of loop
The for-of loop is used to iterate over the values of an iterable object, such as an array or a string.
The variable is assigned the value of each element in the object as the loop iterates over them. Here's an example of a for-of loop that iterates over the elements of an array:
1let numbers = [1, 2, 3, 4, 5];
2
3for (let number of numbers) {
4 console.log(number);
5}
6
This loop will print the numbers 1 through 5 to the console.
Conclusion
For loops are a powerful tool in JavaScript and can be used to perform a variety of tasks, such as iterating over arrays and objects, repeating a block of code a specific number of times, and more. With the three types of for loops available in JavaScript, you can choose the one that best fits your needs and use it to write more efficient and effective code.