Lingua-e
JavaScript

What is a null is not an object?

← Errors

This error appears in JavaScript (especially in Safari and React Native) when you try to access a property or call a method on a value that is null. It is a specific form of TypeError. The most common scenario is querying a DOM element that does not exist yet.

Why it happens

  • Calling document.getElementById() or querySelector() for an element that is not in the DOM at that moment.
  • A variable that should hold an object reference was never assigned or was explicitly set to null.
  • Accessing a property on the result of an API call before the data has loaded.
  • Running DOM queries in a script that executes before the page has fully rendered.

Examples

JavaScript

Code that triggers the error

const button = document.getElementById("submit");
button.addEventListener("click", () => {
  console.log("clicked");
});

Error output

TypeError: null is not an object (evaluating 'button.addEventListener')

How to fix it

Always check if the result of a DOM query is not null before calling methods on it. Use optional chaining (?.) as a concise guard. For API data, use conditional rendering or loading states. Move script tags to the end of the body or use DOMContentLoaded to ensure the DOM is ready.

Fixed code

const button = document.getElementById("submit");

// Guard against null before calling methods
if (button) {
  button.addEventListener("click", () => {
    console.log("clicked");
  });
}

// Or with optional chaining:
button?.addEventListener("click", () => {
  console.log("clicked");
});

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free