Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with strange condition

Tags:

javascript

I came across this snippet reading MDN's tutorial "A re-introduction to JavaScript (JS tutorial)":

function countChars(elm) {
  if (elm.nodeType == 3) { // TEXT_NODE
    return elm.nodeValue.length;
  }
  var count = 0;
  for (var i = 0, child; child = elm.childNodes[i]; i++) {
    count += countChars(child);
  }
  return count;
}

What I don't understand is the for loop statement. Specifically, the condition statement child = elm.childNodes[i]. I always learned that the condition in a loop should be a logical one. For me, that's an assignment.

What am I losing?

like image 938
borjagvo Avatar asked Apr 21 '26 19:04

borjagvo


2 Answers

When the i in child = elm.childNodes[i] is bigger than the length of the array, the deklaration gets evalutated to undefined. And in js undefined is equal to false Boolean(undefined) -> false.

Because of that, this is a boolean equation.

That kind of equation is danger because if the array contains an element that is equal to false (null, 0, false), the loop will stop without iterating all elements.

like image 145
Reiner Avatar answered Apr 23 '26 09:04

Reiner


The condition of for loop here is the value of the assignment oprator = (which is in other words the value elm.childNodes[i]).

var a,
    assignmentOperatorValue = ( a = 5 );
//                            ^^^^^^^^^ this yields 5 which is then assigned to assignmentOperatorValue, you can even pass that value to a function like: func(a = 5);
    
console.log(assignmentOperatorValue);

If elm.childNodes[i] is an element (truthy value) then the condition is true.

If elm.childNodes[i] is undefined (falsy value) then the condition is false.

like image 29
ibrahim mahrir Avatar answered Apr 23 '26 07:04

ibrahim mahrir