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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With