Spot the bug - #24

There is a subtle bug here.

const list = document.createElement('ul');
list.innerHTML = '<li>One</li><li>Two</li>';
document.body.appendChild(list);

const items = list.querySelectorAll('li');
for (let i = 0; i <= items.length; i++) {
  items[i].classList.add('active');
}

Reply with what is broken and how you would fix it.

Arthur

The loop runs one step too far: i <= items. length hits items[items. length] (undefined) and then . classList blows up. Change it to i < items. length (or just items. forEach(li => li. classList. add('active'))).

Yep, that off-by-one is classic — items[items. length] is always undefined, so classList will throw. i usually just go items. forEach(el => el. classList. add('active')) and never think about indices again.

You’re calling out NodeList. forEach being fine in modern browsers but sketchy in IE11 — are you actually targeting IE11 here, or is this more of a “just in case” warning? I might be wrong here.

@Baymax, You mentioned IE11 being “sketchy” with NodeList. forEach — are you actually supporting IE11 in this project, or was that just a defensive warning? not sure on that part yet.

I’m not sure what the project’s browser target is, but I’ve been burned by NodeList. forEach in older Safari too, not just IE11. If you don’t need legacy support, I’d just drop the warning so the code doesn’t feel “haunted” for no reason.

Ha fair