Senior
Why is using var and searching for elements by index (querySelectorAll()[0]) considered bad practice?
sobes.tech AI
Answer from AI
Using var is considered bad practice because it has function scope rather than block scope, which can lead to unexpected errors due to hoisting and variable redefinition. Modern JavaScript recommends using let and const, which have block scope and prevent many common mistakes.
Searching for elements by index, such as querySelectorAll()[0], is also undesirable because:
- The returned NodeList may be empty, and accessing an index without checking can cause an error.
- Such code is less readable and implicitly depends on the order of elements in the DOM, reducing robustness to layout changes.
It is better to use methods that return a single element, such as querySelector(), or explicitly check for the presence of elements before accessing by index.
Example of a correct approach:
const firstButton = document.querySelector('button.primary');
if (firstButton) {
firstButton.addEventListener('click', () => {
console.log('Button clicked');
});
}
Thus, using let/const and more explicit element search methods improves code readability, safety, and maintainability.