Deepika Rao
Deepika Rao

Reputation: 155

for loop without condition checking

I was reading through this question, I am not able to grasp the concept used for the 'for loop'

Generally, syntax of for loop is for(assign value, check condition, increment){} They have used the for loop but there is no condition checking, how does this work?

for(var i = arr1.length; i--;) {
    if(arr1[i] !== arr2[i])
        return false;
}

Upvotes: 4

Views: 13306

Answers (3)

adeneo
adeneo

Reputation: 318362

Actually, it's

for ([initialization]; [condition]; [final-expression])

where all three expressions are optional.

In this case, i-- is a condition, when it reaches 0 it's falsy, and the loop stops.
The "final-expression" is the one not used here.

var arr = [1, 2, 3, 4];

for (var i = arr.length; i--;) {
  console.log(arr[i]);
}

The for statement sets the value of i to a positive integer, then on each iteration it evaluates the condition, effectively decrementing i until it reaches a number that is falsy, which happens when i reaches zero.


Here's some other examples of how to skip expressions in a for loop

Skipping the initialization

var i = 0;
for (; i < 4; i++) {
    console.log(i);
}

Skipping the condition

for (var i = 0;; i++) {
   console.log(i);
   if (i > 3) break;
}

Skipping everything

var i = 0;

for (;;) {
  if (i > 4) break;
  console.log(i);
  i++;
}

Upvotes: 18

jedi_rockstar
jedi_rockstar

Reputation: 1

All the three arguments in a for loop is optional.

Here the loop iterates with i value changing from arr1.length -> 1. Decrementing i is done in the second argument itself. Since the second argument is for condition checking it will return a falsy value when i becomes zero, and the iteration stops. If the arrays don't match the loop will return false in the middle.

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

See the code carefully

for(var i = arr1.length; i--;) {
    if(arr1[i] !== arr2[i])
        return false;
}

Whenever the browser encounters the return statement the control is moved outside the for loop and even outside the function containing this for loop. So, the loops breaks without having a condition when the condition arr1[i] !== arr2[i] is satisfied.

Upvotes: 0

Related Questions