Skip to content Skip to sidebar Skip to footer

Javascript Array Iteration - Mdn Example

I was reading the re-introduction to JavaScript on the MDN website and came across this example in the Array section: for (var i = 0, item; item = a[i++];){ // Do something with

Solution 1:

i++ is the post increment operator, which means that it increments i by 1 but evaluates to the old (non-incremented) value.

> i = 0
  0
> i++
  0
> i
  1

Solution 2:

i++ is post increment (see other answers) and item will not be undefined, because the predicate (the second part in the for loop) is executed before each iteration.

for (var i = 0, item ; item = a[i++];) {

will evaluate to:

var i = 0;
var item;

item = a[i];  // loop
i += 1if (!item) // exit loop// loop body// start again at loop

The problem with this syntax is, that if a value in a is falsy, the loop will terminate prematurely.

var a = [1,2,0,3,4];
for (var i = 0, item ; item = a[i++];) {
   console.log(item);
}

Will output "1 2" because "0" is falsy and the loop terminates

Solution 3:

i++ means that javascript reads the i value and then increments it

Post a Comment for "Javascript Array Iteration - Mdn Example"