0

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 item
}

Where "a[]" is an array being looped over.

I am confused about the value that "item" will have in its first iteration. As i=0 and item is at first undefined, then when it is assigned the value of a[i++] wouldn't the iteration start from i=1, which would mean that the iteration would start from the second element in the a[] array -> a[1], skipping over the first element a[0] entirely?

2
  • 1
    Note that as soon as the current element in the array is 0 or false, the loop will end. Commented May 13, 2013 at 16:24
  • This is one of the worst possible for loops I have seen in JavaScript before. You manage to save 1-2 characters. But sacrifice the usefulness of the index variable and readability. Commented May 13, 2013 at 16:58

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Note that in some languages ++i also exists, it does pre-incrementing, so it has the new value right away.
++i also exists in JS if one would like to use it
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 += 1
if (!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

1 Comment

There are so many unexpectedly falsey values in JavaScript. Just look at this, for example.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.