0

So I've got this piece of code below:

var divs = ["A", "B", "C"];
for (var i = 0, div; div = divs[i]; i++) {  
  print(div);
}

As I understand it, the for loop iterates through every element of the divs array and prints them. I however fail to understand how the loop terminates. Could somebody explain that to me?

2 Answers 2

4

The loop terminates because div = divs[i] will be undefined when i is out of bounds.

Since undefined is a falsey value, the condition is considered to have not been met, and the loop stops.

Note that you're doing an assignment, and not a comparison. The assignment expression returns the value that was assigned, and that value is used for the condition.

You should also note that this technique is reliable only if none of the members of the Array are falsey. If there was a 0 in the Array for example, it would terminate early.

Sign up to request clarification or add additional context in comments.

Comments

2

The part of the for loop that defines whether or not to terminate is the second part:

div = divs[i]

Normally, you would use i < divs.length which yields true or false. Here, the expression evaluates to "A", "B", "C", and undefined, subsequently. undefined acts like false here: it terminates the loop. That's because undefined is a "falsy" value like false is. (The letter strings are not.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.