Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting Condition in For Loop

Can someone please help me understand why the following code works:

var someNumbers = [1,2,3,4,5];
var length = someNumbers.length;

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

How does this for loop know to terminate once i equates to 0? What about negative numbers? Wouldn't this cause an infinite loop?

like image 689
markmiller Avatar asked Jan 09 '23 15:01

markmiller


2 Answers

In Javascript, anything can be a condition! In this case, it's i--. Once i-- returns 0 the loop will stop because 0 is falsy.

The part that's missing is the third expression (the "final expression", see MDN page on the for loop) where you usually find the increment/decrement operation, but both are combined in the "condition" expression in this case.

like image 131
dee-see Avatar answered Jan 12 '23 04:01

dee-see


This is how for loops work. MDN covers for loops in a lot of detail, but to paraphrase:

Syntax

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

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

0 in JavaScript is falsy - this means that it evaluates to false when evaluated as a Boolean expression.

What your for loop essentially does is assign the value stored in your length variable to your i variable, then subtracts 1 from it every time the loop iterates. Eventually, your i variable will be equal to 0. Here it will stop looping and move on to the next statement after the for loop.

This would create an infinite loop if your length variable was negative, but that shouldn't happen with the code you've provided.

like image 33
James Donnelly Avatar answered Jan 12 '23 05:01

James Donnelly