JS while loop array[i++]. How does it work?

I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "result"?

function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l < lLen && r < rLen){
     if(left[l] < right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  return result.concat(left.slice(l)).concat(right.slice(r));
}

Thank you.

Answers


result.push(right[r++]);

is essentially shorthand for

result.push(right[r]);
r = r + 1;

The ++ operator after the variable returns the variable's value before it gets incremented.

For comparison, using it before the variable

result.push(right[++r]);

would achieve the same result as

r = r + 1;
result.push(right[r]);

right[r++] is same like writing this:

right[r]
r=r+1

This was called post-increment. There is also pre-increment. It would be written like this:

right[++r]

It would be eqvivalent to

r=r+1
right[r]

Need Your Help

jQuery not calling my function?

php jquery twitter-bootstrap

I have recently started learning jquery to improve my website. I wanted to make a login modal dialog for users to input their credentials on... I started with this code:

How do you check if Record exists

c# asp.net linq entity-framework

I have a form that does an insert. I want to see if the record already exists in the database to prevent duplicates. I am a little unsure of when this has to go down. In the codebehind for the con...