4

I have an array items. I need to make sure that in the current iteration of the loop I can safely call the next item of the array

for(var i = 0; i < items.length; ++i) {

  // do some stuff with current index e.g....
  item = items[i];


   // then do something with item @ i+1
   if(items[i+1]) {
      //do stuff 
   }

}

Is this how it is done or if not how/what would be the better way?

P.S. I do not want to do a bound check

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 6
    The best way would be to replace `i < items.length` with `i < items.length-1`. Then, you can safely call `items[i+1]` inside your loop. – blex Aug 23 '15 at 15:20
  • 1
    @blex That should be an answer – user229044 Aug 23 '15 at 15:21
  • @meagar I don't feel like posting it as an answer, but please do, if you think it deserves it ;) – blex Aug 23 '15 at 15:22
  • @blex thanks that's a neat trick...but `if(items[i+1])` can be considered safe or not? – Dumbo Aug 23 '15 at 15:41
  • `if(items[i+1])` is not very safe, if, for example, your array contains any _falsey_ values, like `false`, `""` or `0` (your condition won't be met, the `if` statement won't be executed). A better way to check that _there is_ an element at index `i+1` would be to do `if(i – blex Aug 23 '15 at 15:43
  • take a look to this question http://stackoverflow.com/questions/6728424/array-out-of-bounds-comparision-with-undefined-or-length-check – Mido Aug 23 '15 at 22:59

3 Answers3

5

If you want to loop through every element except the last one (which doesn't have an element after it), you should do as suggested:

for(var i = 0; i < items.length-1; ++i) {
    // items[i+1] will always exist inside this loop
}

If, however, you want to loop through every element -even the last one-, and just add a condition if there is an element after, just move that same condition inside your loop:

for(var i = 0; i < items.length; ++i) {
    // do stuff on every element
    if(i < items.length-1){
        // items[i+1] will always exist inside this condition
    }
}

if(items[i+1]) will return false (and not execute the condition) if the next element contains a falsey value like false, 0, "" (an empty String returns false).

blex
  • 24,941
  • 5
  • 39
  • 72
4

Put a value check on variable i and make sure it is less than items.length-1 in order to safely access items[i+1].

for(var i = 0; i < items.length-1; ++i) {

  if(items[i+1]) {
    //do stuff 
  }

}
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
  • 1
    Actually, i needed to break the loop between an if and an else, your answer helps a lot because one can't break array.forEach in a goog way like the old fashion loop for does – Andres Felipe Nov 15 '20 at 16:06
3

Drop the for loop and use array#forEach, and simply check whether a next value exists:

items.forEach(function (item, index) {

  if (!items[index + 1]) return;

  // do something with item and items[index + 1]
});
user229044
  • 232,980
  • 40
  • 330
  • 338