LoveAndHappiness
LoveAndHappiness

Reputation: 10135

Javascript: Forloop Difference between i++ and (i+1)

I was building a javascript for loop and I want to compare the value of an array to the next value in the array.

If both values are not equal, I want to return true, otherwise I want to return false.

In the code below I pass the string "aba", split it and sort it to

sortedLetters = ["a", "a", "b"]

Yet, when I compare sortedLetters[0] ("a") with sortedLetters[1]

function isIsogram(str){

    // split each letter into an array and sort
    sortedLetters = str.split("").sort();

    console.log(sortedLetters[0]); // is "a"
    console.log(sortedLetters[1]); // should be "a"

    // iterate through the array and see if the next array is equal to the current
    // if unequal, return true
    for( i = 0; i < sortedLetters.length; i++ ) {
        if(sortedLetters[i] !== sortedLetters[(i+1)]) return true;
    }
    // for "a" and "a", it should return false

    return false;

};

document.write(isIsogram("aba"));

Yet, why does the following if statement work, but the above code does not?

if(sortedLetters[i] !== sortedLetters[i++]) return true;

Upvotes: 1

Views: 349

Answers (2)

rnevius
rnevius

Reputation: 27102

Quite simply, the indexes are the same in this expression:

if(sortedLetters[i] !== sortedLetters[i++]) return true;

If the for loop counter is at 3, for example, it will evaluate sortedLetters[3] !== sortedLetters[3] before incrementing the value.

Using i++ in your for loop will also double-increment your counter.

Upvotes: 1

Guffa
Guffa

Reputation: 700362

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code:

if(sortedLetters[i] !== sortedLetters[i++]) return true;

does the same thing as:

if(sortedLetters[i] !== sortedLetters[i]) return true;
i = i + 1;

As x !== x always is false for any stable value of x, the code does the same thing as:

if(false) return true;
i = i + 1;

You can use the pre increment version ++i, but if you increment the variable in the statement, you shouldn't increment it in the loop also:

for (i = 0; i < sortedLetters.length; ) {
  if (sortedLetters[i] !== sortedLetters[++i]) return true;
}

Upvotes: 2

Related Questions