Search code examples
javascriptfor-loopforeachundefined-behavior

forEach failure at undefined array


For a very long time I used

for (var n in nodes) {f(nodes[n])} 

quite successfully. But, switching to the neat

nodes.forEach(f)

I have noticed that it fails at undefined nodes, whareas for-in loop did not. I wonder, how can I make forEach to operate identically?


Solution

  • Well, you can't. Because .forEach is just a function, and you can't call a function on null/undefined. What you could do is:

    (arr || []).forEach(f);
    

    But for these cases I recommend to use the for of loop or the regular for loop, which are both identical to .forEach. for in has a different semantic.