Understand the idea
An error message is evidence, not a verdict on your ability. Read its type, message and source location. Begin with the first relevant error, because later failures may be consequences.
A selector can return null when no element matches. Calling addEventListener on that value fails before the click can ever happen. Check the exact selector, the HTML and whether the script runs after the element exists.
Read the example
Use a button with id="show-hint" and a hidden paragraph with id="hint". Load the script with defer.
// Use this in a deferred external script.
const button = document.querySelector("#show-hint");
const hint = document.querySelector("#hint");
if (!button || !hint) {
console.error("Expected #show-hint and #hint in the document.");
} else {
button.addEventListener("click", () => {
hint.hidden = false;
});
}A four-step debugging note
- Expected: write down what the action should do.
- Observed: record the message and the visible behaviour.
- Hypothesis: identify one possible cause.
- Test: change one thing and repeat the original action.
Check loading before logic
If no message appears at all, confirm that the script was requested successfully. A file that never loaded cannot execute a debugging statement. Do not paste unfamiliar code into your console to “fix” an unrelated website.
Practise: a selector that finds nothing
A small mistake, explained
What goes wrong
Adding optional chaining everywhere can silence a missing-element error while leaving the required interface broken.
How to fix it. For required elements, make the mismatch visible during development and correct it. A guard is appropriate for intentionally optional features, but is not a replacement for checking the markup.
Try it yourself
Create the two elements, then deliberately misspell the button id. Read the message, repair the id, reload and test the action again.
Further reading
MDN — Read the first useful error (new tab)
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Conditions & comparisonsMake a decision without accidentally changing the value.