Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ' Array ' and ' Loop ' how can " variable[i] " be a CONDITION

Here in this script cars[i] is used as a condition how is does the program identify weather the condition is true or false and the program stops correctly after it enters the 4th variable in the array ?

So the question is : how the program identifies the condition and how is cars[i] a condition.

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";

for (;cars[i];) {
    text += cars[i] + "<br>";
    i++;
}
like image 956
CoDINGinDARK Avatar asked Mar 30 '15 06:03

CoDINGinDARK


1 Answers

Two things are at work here:

  1. In JavaScript, when you use a value as a condition, it's coerced to be a boolean. The values 0, "", NaN, null, and undefined coerce to false (they, plus false, are called "falsey" values); all others ("truthy values") coerce to true.

  2. If you try to access a non-existant entry in an array, you get back undefined.

So when i reaches 4, cars[i] is undefined, which coerces to false, and the loop stops. But relying on that is likely to be setting a trap, because if there are any entries in cars that coerce to false (there aren't in that example, but...), the loop will stop before processing the entire array.


Side note: for (; condition ;) is a very strange way to write while (condition). If you don't have initialize, test, and update parts, for probably isn't the control structure you want. You've said you're trying to understand this code, so I'm guessing you didn't write it; just beware that the quality may not be that high.

Here's the "normal" way to write that loop:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i;
var text = "";
for (i = 0; i < cars.length; i++) {
    text += cars[i] + "<br>";
}

Or something a bit more modern:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";
cars.forEach(function(car) {
    text += car + "<br>";
});

Or something a bit more advanced, but perhaps offputting for beginners:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = cars.reduce(function(acc, car) {
    return acc + car + "<br>";
}, "");
like image 153
T.J. Crowder Avatar answered Nov 14 '22 23:11

T.J. Crowder