Search code examples
javascriptdomdom4

hasChildNodes vs firstChild


while (div.hasChildNodes()) {
    fragment.appendChild(div.firstChild)
}

while (div.firstChild) {
    fragment.appendChild(div.firstChild)
}

Comparing the two pieces of pseudo code above, they both append each child of div to fragment until there are no more children.

  1. When would you favour hasChildNodes or firstChild they seem identical.
  2. If the APIs are so similar then why do they both exist. Why does hasChildNodes() exist when I can just coerce firstChild from null to false

Solution

  • a) micro-optimization!

    b) Although it seems to be common practice, I'm not fond of relying on null/non-null values being used as a substitute for false/true. It's a space saver that's unnecessary with server compression enabled (and can sometimes call subtle bugs). Opt for clarity every time, unless it's demonstrated to be causing bottlenecks.

    I'd go for the first option, because it explains your intent perfectly.