Reputation:
I wanted to write below code with For loop having multiple conditions but it didn't work. Please point the mistake I made.
// Working as expected
bs = [false, true, false];
for (let i = 0; i < 3; i++) {
if (bs[i]) {
console.log('Hi', i);
}
}
Code that is not working as expected
// Not working as expected
bs = [false, true, false];
for (let i = 0; i < 3 && bs[i]; i++) {
console.log('Hi', i);
}
Upvotes: 0
Views: 601
Reputation: 16908
The entire for loop is exiting as the exit condition is evaluated to false
due to the i < 3 && bs[i]
expression. So in the first iteration itself the loop sees the false
value in the array and it exits as i < 3 && bs[i]
is becoming false
so nothing is printed.
There is no way to skip an iteration in the exit check in the for loop, you can either use an if
as per your first snippet and conditionally print or you can use continue
to skip an iteration depending on the value you get from the supplied array:
const bs = [false, true, false];
for (let i = 0; i < 3; i++) {
if(bs[i] === false){
//skips this iteration
continue;
}
console.log('Hi', i);
}
You can also use the forEach
method of an array:
const bs = [false, true, false];
bs.forEach((o,i) => o !== false && console.log("Hi", i));
Upvotes: 1
Reputation: 35
Looks alright! The second parameter of a for loop tells the interpreter about when to stop the loop. In the first for loop, the loop continues until i reaches 3, while in the second loop, the loop immediately cuts off since the first condition returns false and indicates the interpreter to stop.
Upvotes: 1
Reputation: 14305
The second for loop stops the moment its condition evaluates to false. It's not like it skips a false value.
Since the first value in the array in false
, the for loop doesn't run its body once.
Upvotes: 1