Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 267
Tima Tru Avatar asked Jan 14 '16 18:01

Tima Tru


People also ask

How does while loop work in JavaScript?

Definition and Usage. The while statement creates a loop (araund a code block) that is executed while a condition is true . The loop runs while the condition is true . Otherwise it stops.

Can you use a while loop for an array?

Using while to iterate over an array We can even use while loops to iterate over an array. First we define an array and find out its length, len , using the length property of arrays. Then we define an index variable to iterate over the array .

How does a while loop start?

Syntax. The while loop starts by evaluating condition . If condition evaluates to true , the code in the code block gets executed. If condition evaluates to false , the code in the code block is not executed and the loop ends.

How does do while loop work?

In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.


1 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]);
like image 181
Lucas Avatar answered Oct 03 '22 22:10

Lucas