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,
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.
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;
}