Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "undefined" end a loop in JavaScript?

Tags:

People also ask

Why does JavaScript loop only use the last value?

You have some sort of for/next loop that then calls some asynchronous function. When the function runs, what you see when the code runs is that the last value of the loop index is the value that gets used in the function for every instance that it gets called.

How do you stop a loop in JavaScript?

You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.

What will happen if while loop runs indefinitely in JavaScript?

An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer.

Why are returns undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .


I am having trouble understanding how this for-loop terminates in JavaScript:

var files = ["A", "B"];
for (var i = 0, f; f = files[i]; i++) {
   console.log(f);
}

When run, it displays A and B on the screen, but why does f=files[2] end the loop? If I run f=files[2] in my console I get the answer "undefined", so what is the rationale behind the fact that this should end the loop?

Bonus question: Why not write the loop instead as the following?

for (var i=0; i < files.length; i++) {
    f = files[i];
    console.log(f);
}

This seems clearer and more maintainable to me, so is there some reason that the first piece of code would be used over the second?