null values
data validation
programming
software development
error handling

What is the proper way to check for null values?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

There is no single universal null check that works the same way in every language or every data system. The proper way depends on both the platform and your intent: do you want to detect an absent reference, distinguish null from other empty values, or write a query that handles missing data correctly.

Start With the Meaning of "Null"

Programmers often mix several ideas together:

  • a missing reference such as null or None
  • an empty value such as "", [], or 0
  • an undefined variable or missing property
  • a database NULL

Those are not interchangeable. The first step in "proper" null checking is deciding which one you actually mean.

Null Checks in Common Languages

In Java, checking whether a reference is missing is direct:

java
1String name = getName();
2if (name == null) {
3    System.out.println("name is missing");
4}

For ordinary reference checks, == null is the normal and readable choice. Avoid calling methods before that check.

In Python, the idiomatic test is is None, not == None:

python
value = get_value()
if value is None:
    print("missing value")

is None tests identity, which is the intent for Python's singleton None.

In JavaScript, the right check depends on whether you want to treat null and undefined the same way:

javascript
1const value = getValue();
2
3if (value === null) {
4  console.log("strictly null");
5}
6
7if (value == null) {
8  console.log("null or undefined");
9}

The loose equality form == null is one of the rare cases where non-strict comparison is intentionally useful, because it matches both null and undefined without also matching empty strings or zero.

Database Null Checks Are Different

SQL NULL does not behave like ordinary values. Comparing with = does not work. You must use IS NULL or IS NOT NULL.

sql
SELECT id, email
FROM users
WHERE email IS NULL;

This is a common source of bugs for developers who move between application code and SQL. email = NULL is not true; it evaluates to unknown in SQL's three-valued logic.

Prefer Early Checks and Clear Contracts

Null handling is easier when you decide at API boundaries what is allowed. For example, instead of checking for null everywhere in the middle of the code, validate inputs early:

java
1public void sendEmail(String address) {
2    if (address == null) {
3        throw new IllegalArgumentException("address must not be null");
4    }
5
6    System.out.println("Sending to " + address);
7}

This makes failures immediate and easier to debug.

In Python, the same idea can be expressed with guard clauses:

python
1def send_email(address: str | None) -> None:
2    if address is None:
3        raise ValueError("address must not be None")
4
5    print(f"Sending to {address}")

The best null check is often the one that narrows the scope of nullable values as early as possible.

Null-Safe Access Patterns

Sometimes you do not want a hard failure; you want safe access with a fallback.

In JavaScript:

javascript
const city = user?.profile?.address?.city ?? "unknown";
console.log(city);

This avoids throwing when an intermediate property is absent.

In Java, Optional can help express values that may or may not exist:

java
1import java.util.Optional;
2
3Optional<String> nickname = findNickname();
4String displayName = nickname.orElse("guest");
5System.out.println(displayName);

These features are not replacements for reasoning about null, but they often make intent clearer.

Common Pitfalls

The most common mistake is treating empty values as null values. An empty string is not the same as null, and 0 is not the same as a missing number. If your logic merges them together, subtle bugs follow.

Another mistake is using equality when identity is the idiomatic rule, especially in Python. value is None communicates intent more clearly than value == None.

A third issue is forgetting that SQL uses different rules. WHERE column = NULL does not filter null rows correctly; use IS NULL.

In JavaScript, broad falsy checks also cause trouble. Code like if (!value) treats 0, false, "", null, undefined, and NaN the same way. That is fine only when you genuinely want all of them grouped together.

Finally, repeated null checks deep inside business logic usually signal weak data contracts. If a value may be absent, encode that clearly at the boundaries instead of scattering defensive checks everywhere.

Summary

  • The proper null check depends on the language and on what "missing" means in context.
  • Use == null in Java, is None in Python, and the appropriate strict or loose check in JavaScript.
  • In SQL, use IS NULL and IS NOT NULL, not = NULL.
  • Distinguish null from empty strings, zero, false, and other non-null values.
  • Prefer early validation and clear API contracts over repeated ad hoc null checks.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.