📜  for of - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:18.182000             🧑  作者: Mango

For Of - JavaScript

In JavaScript, the for of loop is used to iterate over iterable objects such as arrays, strings, and maps. Unlike the traditional for loop, it does not loop through the values or keys of an object, but rather it loops through the iterable objects. This loop simplifies the code and makes it easier to read and write.

Syntax
for (variable of iterable) {
  // Code block to be executed
}

Variable: A variable that represents each item of an iterable object during the iteration.

Iterable: An object that has the Symbol.iterator method, which is called when the loop is initiated to return an iterator object.

Example
const fruits = ['apple', 'orange', 'banana'];

for (const fruit of fruits) {
  console.log(fruit);
}
// Output: 
// apple
// orange
// banana

In the above example, the for of loop is used to iterate over an array of fruits. The variable fruit represents each item of the array during each iteration of the loop, and its value is printed on the console.

Benefits of Using For Of Loop
  • Simplifies the syntax and makes it easier to read and write.
  • Provides a more concise and cleaner code.
  • Improves the performance of the code because it is optimized to loop through iterable objects.
  • Reduces the chances of making mistakes when writing looping conditions.
Limitations of For Of Loop
  • Cannot be used to loop through an object's properties directly.
  • Cannot skip or break the loop early without throwing an exception.
  • Not supported by older browsers.
Conclusion

The for of loop in JavaScript provides a simple and efficient way to iterate over iterable objects. It simplifies the code and makes it easier to read and write. However, it has some limitations and is not supported by older browsers. Therefore, it is recommended to use it in modern web development projects.