Which loop in JavaScript is used to iterate over the elements of an ar...
The 'for...of' loop in JavaScript is used to iterate over the elements of an array.
In JavaScript, loops are used to execute a block of code repeatedly until a certain condition is met. The 'for...of' loop is specifically designed for iterating over the elements of an array or any other iterable object in a concise and readable manner.
How does the 'for...of' loop work?
The 'for...of' loop provides an easy and straightforward way to iterate over the elements of an array without the need for manual indexing or tracking the length of the array. It follows the syntax:
```
for (variable of iterable) {
// code to be executed for each element
}
```
Key points about the 'for...of' loop:
- The 'variable' represents a new variable that will be assigned the value of each element in the 'iterable' object on each iteration.
- The 'iterable' object can be an array, a string, or any other iterable object in JavaScript.
- On each iteration, the 'variable' takes the value of the next element in the 'iterable' object until all the elements have been iterated.
- The loop automatically handles the iteration process and does not require manual indexing or specifying the length of the array.
- The 'for...of' loop can only be used for forward iteration and does not provide access to the index of each element in the array.
- The loop terminates when all the elements in the 'iterable' object have been processed.
Example:
Let's consider an example to demonstrate the usage of the 'for...of' loop:
```javascript
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
}
```
In this example, the 'for...of' loop is used to iterate over each element in the 'numbers' array. On each iteration, the 'num' variable takes the value of the next element in the array, and it is logged to the console. The output will be:
```
1
2
3
4
5
```
The 'for...of' loop simplifies the process of iterating over the elements of an array and provides a more readable and concise syntax compared to other types of loops in JavaScript.
Which loop in JavaScript is used to iterate over the elements of an ar...
The for...of loop is used to iterate over the elements of an array.
To make sure you are not studying endlessly, EduRev has designed Software Development study material, with Structured Courses, Videos, & Test Series. Plus get personalized analysis, doubt solving and improvement plans to achieve a great score in Software Development.