121k views
0 votes
What is the difference between the forEach, for-of, and for-in loops?

A. 'ForEach' is used to iterate over the properties of an object, 'for-of' is used to loop through the elements of an array, and 'for-in' is used to iterate over the values in a Map.
B. 'ForEach' is primarily used for asynchronous operations, 'for-of' is used for synchronous iteration, and 'for-in' is used for conditional loops.
C. 'ForEach' is a higher-order function that applies a provided function once to each element in an array, 'for-of' is used for iterating over iterable objects, and 'for-in' is used to iterate over the keys of an object.
D. 'ForEach' is used to loop through array elements with a break and continue statement, 'for-of' is used to loop through the properties of an object, and 'for-in' is used to perform conditional checks.

User Kapoor
by
8.1k points

1 Answer

5 votes

Final answer:

The forEach loop applies a given function to each array element, for-of iterates over iterable objects, and for-in iterates over the keys of an object.

Step-by-step explanation:

The difference between the forEach, for-of, and for-in loops is as follows:

  • forEach is a higher-order function that applies a given function once to each element in an array, but cannot be broken out of early using the break or continue statements.
  • for-of loop is designed to iterate over iterable objects such as arrays, strings, maps, nodeLists, and more, providing a way to access the values directly with a simpler syntax compared to traditional for loops. The for-of loop also supports break, continue, and return within the block to control the flow.
  • for-in loop is especially useful for iterating over the keys of an object, but it is not recommended for iterating over arrays as the order is not guaranteed and it may enumerate through non-element properties.

The correct option from the given choices would be C: 'ForEach is a higher-order function that applies a provided function once to each element in an array, for-of is used for iterating over iterable objects, and for-in is used to iterate over the keys of an object.'

User Dumdum
by
7.3k points