Real‑world examples of handling null pointer exceptions in JavaScript
Everyday examples of handling null pointer exceptions in JavaScript
Let’s skip the theory and get straight into real examples of handling null pointer exceptions in JavaScript. These are the kinds of bugs that actually show up in logs, Sentry dashboards, and user bug reports.
Example of guarding against missing DOM elements
Classic front‑end bug:
// Old jQuery-style or vanilla JS code
const sidebar = document.querySelector('.sidebar');
sidebar.classList.add('is-open'); // 💥 TypeError: Cannot read properties of null
If .sidebar doesn’t exist on some pages, sidebar is null and you get a null pointer‑style error. Safer pattern:
const sidebar = document.querySelector('.sidebar');
if (sidebar) {
sidebar.classList.add('is-open');
}
Or with optional chaining and a helper:
const addClassIfPresent = (selector, className) => {
document.querySelector(selector)?.classList.add(className);
};
addClassIfPresent('.sidebar', 'is-open');
This is one of the best examples of how optional chaining (?.) makes handling null pointer exceptions almost effortless in modern JavaScript.
API response handling: examples include null fields and missing data
Backend APIs rarely behave exactly the way front‑end code expects. Here’s a common pattern:
// Expecting user.profile.avatarUrl to exist
const avatarUrl = user.profile.avatarUrl; // 💥 user.profile is null
A safer, 2024‑style version:
// Use optional chaining and nullish coalescing
const avatarUrl = user?.profile?.avatarUrl ?? '/images/default-avatar.png';
If user or profile is null or undefined, the expression short‑circuits and you fall back to a default image. This is one of the clearest examples of handling null pointer exceptions in JavaScript without giant if nests.
For more defensive code, especially when consuming external APIs, add runtime validation. A lot of teams now pair TypeScript with runtime schema validation libraries like Zod or Joi:
import { z } from 'zod';
const UserSchema = z.object({
id: z.string(),
profile: z
.object({
avatarUrl: z.string().url().nullable().optional(),
})
.nullable()
.optional(),
});
function safeParseUser(json) {
const result = UserSchema.safeParse(json);
if (!result.success) {
// log and return a safe fallback
return { id: 'anonymous', profile: null };
}
return result.data;
}
By validating at the edges, you turn unpredictable null values into predictable shapes, which is one of the best examples of how modern tooling reduces null pointer exceptions across a large codebase.
Real examples from React components
React apps are fertile ground for null pointer issues, especially when data loads asynchronously.
Example of conditional rendering with optional chaining
function UserProfile({ user }) {
// Risky: user might be null while data loads
return (
<div>
<h1>{user.name}</h1> {/* 💥 Cannot read properties of null */}
</div>
);
}
Safer pattern using conditional rendering:
function UserProfile({ user, isLoading }) {
if (isLoading) return <p>Loading…</p>;
if (!user) return <p>User not found.</p>;
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email ?? 'Not provided'}</p>
</div>
);
}
Or a terser version with optional chaining in JSX:
function UserProfile({ user }) {
return (
<div>
<h1>{user?.name ?? 'Unknown user'}</h1>
{user?.email && <p>Email: {user.email}</p>}
</div>
);
}
These React patterns are strong examples of handling null pointer exceptions in JavaScript UI code without littering everything with try/catch.
Node.js: example of defensive environment and config handling
Server‑side JavaScript sees its own flavor of null pointer errors, especially around configuration and environment variables.
// config.js
module.exports = {
dbUrl: process.env.DB_URL, // might be undefined
};
// db.js
const { dbUrl } = require('./config');
connectToDatabase(dbUrl); // 💥 inside connectToDatabase, dbUrl is null/undefined
A more defensive approach:
function requireEnv(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
const config = {
dbUrl: requireEnv('DB_URL'),
};
module.exports = config;
This pattern fails fast at startup instead of throwing a null pointer exception later under production load. In practice, many of the best examples of handling null pointer exceptions in JavaScript on the backend involve validating configuration up front.
Async/await: examples include missing data and rejected promises
Async code hides a lot of null pointer landmines. Consider:
async function getUserName(id) {
const res = await fetch(`/api/users/${id}`);
const data = await res.json();
return data.user.name; // 💥 data.user might be null
}
``;
A safer version:
```js
async function getUserName(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
}
const data = await res.json();
const name = data?.user?.name;
if (!name) {
// Decide on a policy: throw, log, or fallback
return 'Anonymous';
}
return name;
}
This pattern shows an example of combining HTTP error handling with null safety. Real examples from production logs often show a chain of issues: a 500 from the server, then a null pointer exception when the client assumes the JSON shape is always valid.
Example of safe array access and iteration
Arrays are another frequent source of null pointer‑style bugs:
const items = getItems(); // might return null
items.forEach(item => { // 💥 Cannot read properties of null
console.log(item.name);
});
Safer patterns:
const items = getItems() ?? []; // normalize null/undefined to []
for (const item of items) {
console.log(item?.name ?? 'Unnamed item');
}
Or a utility function that normalizes arrays:
function asArray(value) {
if (Array.isArray(value)) return value;
if (value == null) return [];
return [value];
}
const items = asArray(getItems());
These are simple, but they’re some of the best examples of handling null pointer exceptions in JavaScript collections without overcomplicating your code.
TypeScript: examples of preventing null pointer exceptions before runtime
Most large JavaScript teams in 2024–2025 are using TypeScript specifically to catch null pointer problems at compile time. With strict settings, TypeScript forces you to acknowledge null and undefined.
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"strictNullChecks": true
}
}
interface User {
id: string;
name?: string | null;
}
function greet(user: User) {
// Error: Object is possibly 'undefined' or 'null'
console.log(`Hello, ${user.name.toUpperCase()}`);
}
TypeScript forces you into safer code:
function greet(user: User) {
const name = user.name ?? 'friend';
console.log(`Hello, ${name.toUpperCase()}`);
}
Or:
function greet(user: User) {
if (!user.name) {
console.log('Hello, friend');
return;
}
console.log(`Hello, ${user.name.toUpperCase()}`);
}
These are strong examples of how static typing can eliminate entire classes of null pointer exceptions in JavaScript before they ever hit production.
Logging and monitoring: real examples from production behavior
Even with good patterns, some null pointer errors will escape. The teams that handle them well have two habits:
- They log enough context when a null appears.
- They aggregate and monitor those logs.
A simple Node.js pattern:
function safeGet(obj, path, defaultValue = null) {
try {
return path.split('.').reduce((acc, key) => acc?.[key], obj) ?? defaultValue;
} catch (err) {
console.error('Null pointer-like error while accessing path', {
path,
error: err.message,
});
return defaultValue;
}
}
const city = safeGet(user, 'address.city', 'Unknown');
In real examples from production, this kind of utility often sits alongside an error tracking service. While not JavaScript‑specific, resources from organizations like Harvard’s CS50 course and Mozilla Developer Network discuss defensive programming patterns that translate well to avoiding null pointer exceptions.
2024–2025 trends that reduce null pointer issues
If you’re looking for the best examples of handling null pointer exceptions in JavaScript today, you’ll see a few consistent trends:
- Optional chaining and nullish coalescing everywhere. These language features are now standard across modern browsers and Node.js. They turn verbose null checks into clean, readable expressions.
- TypeScript with strict null checks. Most serious projects either start in TypeScript or migrate to it, precisely to tame
nullandundefined. - Schema‑first APIs. Tools like OpenAPI and GraphQL schemas, combined with code generation, help keep client and server in sync so
nullfields are expected and documented. - Runtime validation at boundaries. Libraries like Zod and Joi validate external input (HTTP requests, environment variables, JSON files) so
nulldoesn’t slip into core logic unchecked. - Better testing and monitoring. Unit tests for edge cases, plus production monitoring, catch the weird real‑world examples where user behavior or third‑party APIs introduce unexpected nulls.
While organizations like NIST focus more on security than null pointers specifically, the general guidance on defensive coding and input validation lines up perfectly with the patterns in these examples of handling null pointer exceptions in JavaScript.
Patterns and anti‑patterns: examples of safer JavaScript designs
To wrap the patterns together, here are some design habits that show up repeatedly in real examples.
Prefer explicit defaults over implicit null behavior
Instead of allowing null to leak everywhere, normalize early:
// Anti-pattern
function getTheme(userSettings) {
return userSettings.theme; // might be null
}
// Better
function getTheme(userSettings) {
return userSettings?.theme ?? 'light';
}
This is a small example of how a single ?? 'light' can prevent a chain of null pointer exceptions in JavaScript UI code.
Fail fast at boundaries, not deep inside logic
Rather than letting null bubble into complex logic, validate early:
function createOrder(user, cart) {
if (!user) throw new Error('User is required');
if (!cart || cart.items?.length === 0) {
throw new Error('Cart cannot be empty');
}
// Safe to proceed: user and cart are non-null and non-empty here
}
Many of the best examples from mature codebases show this pattern: short, defensive checks at function boundaries, then simpler logic inside.
Use linters and code review to enforce patterns
Tools like ESLint can catch risky patterns. For example:
{
"rules": {
"no-unsafe-optional-chaining": "error",
"@typescript-eslint/strict-boolean-expressions": "error"
}
}
These rules prevent patterns where optional chaining or falsy checks accidentally allow null or undefined through in unsafe ways.
FAQ: short examples and quick answers
What are common examples of null pointer exceptions in JavaScript?
Common examples include accessing properties on null or undefined (like user.profile.name when user is null), calling methods on missing DOM elements, iterating over null arrays, and assuming API responses always contain nested objects.
Can you show an example of using optional chaining to avoid errors?
Yes. Instead of writing user && user.profile && user.profile.name, you can write:
const name = user?.profile?.name ?? 'Anonymous';
This is one of the clearest examples of handling null pointer exceptions in JavaScript with modern syntax.
Are try/catch blocks a good way to handle null pointer exceptions?
They’re fine for truly exceptional situations, but they’re overkill for everyday null checks. Most examples of good practice rely on optional chaining, nullish coalescing, TypeScript, and validation at boundaries rather than wrapping everything in try/catch.
How do I test for null pointer issues in JavaScript?
Write unit tests that intentionally pass null or undefined into your functions, or mock API responses with missing fields. Many real examples of bugs appear only when data is partially missing, so tests should mirror that.
Is using == null a bad idea?
value == null is a compact way to check for both null and undefined, and many codebases use it intentionally. Just be consistent, and avoid mixing it with loose equality in other contexts. If you prefer strictness, use explicit checks like value === null || value === undefined.
If you adopt even a handful of these patterns, your own examples of handling null pointer exceptions in JavaScript will move from late‑night production outages to small, predictable edge cases you already know how to handle.
Related Topics
Practical examples of debugging null pointer exceptions in C#
Practical examples of testing strategies to prevent null pointer exceptions
Practical examples of how to identify null pointer exceptions in Python
Real-world examples of null pointer exceptions in SQL queries
Best examples of comparing null pointer exceptions vs. other exceptions in real code
Practical examples of using Optional to avoid null pointer exceptions in Java
Explore More Null Pointer Exceptions
Discover more examples and insights in this category.
View All Null Pointer Exceptions