May 8, 2014

Return to the beginning of an array with a ternary operator

Often times when iterating and looping over the contents of an array, I want to set the current index to zero if it's reached the last element. Generally this happens in the form of an if/else statement, but I enjoy using a more terse form with the help of a ternary operator. See the code below, and enjoy!
var myArray = ['one', 'two', 'three', 'four'];
var curIndex = 0;

setInterval(function(){
    console.log(myArray[curIndex]);
    curIndex = (curIndex < myArray.length - 1) ? curIndex + 1 : 0;
}, 500);

1 comment:

  1. the best way:
    var myArray = ['one', 'two', 'three', 'four'];
    var curIndex = 0;

    setInterval(function(){
    console.log(myArray[curIndex]);
    curIndex = ++curIndex%myArray.length;
    }, 500);

    ReplyDelete