Spot the bug - #13

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.

Hari :grinning_face_with_smiling_eyes:

Your loop goes one index past the end: when i === items.length, items[i] is undefined, so items[i].classList.add(...) throws.

Fix is just i < items.length, or skip indexing entirely and iterate the nodes: for (const item of items) item.classList.add('active');.

Yeah this is it β€” you’re hitting items[items. length] which is always undefined, so classList blows up. switching to i < items. length or a for. . . of loop makes it cleaner and harder to mess up.

Classic off-by-one β€” items[items.length] is always undefined (last index is length - 1), so classList is gonna throw.

Switching to i < items.length fixes it, and I’m a fan of for...of here just so you never even touch indexes.

One small defensive tweak: if you keep the index loop, items[i]? . classList. add('active') prevents the throw even if the bounds are wrong (or the NodeList changes under you later). I found a related kirupa. com article that can help you go deeper into this topic: