Fun Planet
Fun Planet

Reputation: 73

What is the difference between for loop and for..of loop?

What is the main difference between for loops and for..of loops in the context of iterating over an array?

Why does this code

for (let n of at.neighbours) {
  DFS(n);
}

give different output than this code?

for (let i = 0; i < at.neighbours.length; i++) {
  n = at.neighbours[i]
  DFS(n);
}

This is my function btw:

function DFS(at) {
  if (at.visited) return;
  at.visited = true
  
  // for (let i = 0; i < at.neighbours.length; i++) {
  //   n = at.neighbours[i]
  //   DFS(n);
  // }
  
  // This gives desired output
  for (let n of at.neighbours) {
    DFS(n);
  }
}

Upvotes: 1

Views: 446

Answers (1)

mappie
mappie

Reputation: 522

Basic Difference

for statement allows you to iterate over iterable objects while controlling the start and the terminating condition.

for...of can also be used to iterate over iterable objects(arrays and array-like objects and user-defined iterables). The operation is executed on the value of each distinct property unless it is terminated by using break, return, or throw keywords.

forEach method is available as a prototype method of iterable objects but it is executed for each element unless an error is thrown. (Ideally should be used only if the operation is to be executed on every element)

In terms of performance,

for statement outperforms all other iteration statements. Refer to this

In terms of support,

  • for statement is supported widely across browsers. Link
  • for...of is still not supported in Internet Explorer. Link
  • forEach is also supported widely for arrays. Link

Upvotes: 4

Related Questions