Garth Marenghi
Garth Marenghi

Reputation: 2037

Second conditional with null value

I have the following piece of code:

function listToArray(list) {
    var array = [];
    for(var node = list; node; node = node.rest) {
      console.log(node.rest);
      array.push(node.value);
    }

    return array;
}

E.g.: An array like [1, 2, 3] would look in list form like this { value: 1, rest: { value: 2, rest: { value: 3, rest: null }}}.

The conditional of the for loop in the function will eventually result in null. My question is, how does this conditional work? Usually you'll have a boolean expression, e.g.: i <= 10. AFAIK, null doesn't evaluate to a falsey value... So how does the conditional work?

Upvotes: 0

Views: 241

Answers (1)

Anmol Mittal
Anmol Mittal

Reputation: 853

The condition in for loop is an expression that is evaluated at each iteration.If it evaluates to true , statement is executed.Since null,0,etc. are counted as false, it doesnt executes.

Source :- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for

Upvotes: 1

Related Questions