CodeBlanks Logo Icon CodeBlanks

Difference between null and undefined

JavaScript course · Beginner · Lesson 4/133

Learn the difference between empty and undefined values and when to use each.

What is undefined?

In JavaScript, if you declare a variable but do not assign a value, that variable automatically holds undefined. The word means not defined: the variable exists but it has no value inside.

For example, let ad; declares the ad variable but its value is undefined. If you then write console.log(ad); the console shows undefined. This happens when you try to read a variable before assigning to it.

What is null?

null is an intentionally given empty value. You are saying the variable will be empty; JavaScript did not forget anything, you said empty for now.

For example, if a user has not yet picked a city you write let sehir = null;. If you then write console.log(sehir); the console shows null. So null says the variable has a value, and that value is empty.

When to use null, when undefined?

undefined is usually a state JavaScript itself produces: you forgot something and the system says no value. null is a value you write on purpose: empty for now, I will fill it later.

In short: when you want to give a variable an empty for now value, use null. When you forget to assign a value, JavaScript automatically gives undefined. In practice you do not write undefined by hand; you write null to mean I meant empty.

Exercise Show undefined first, then null

Declare a pick variable with let but do not assign a value (so it becomes undefined). Then assign null to pick. In both states, print its value with console.log.

Show example solution
let pick;
console.log(pick);
pick = null;
console.log(pick);

Test yourself

  1. Which of these snippets prints undefined to the console?

    • let yas = 30; console.log(yas);
    • let yas = null; console.log(yas);
    • let yas = "30"; console.log(yas);
    • let yas; console.log(yas);
    Show answer

    let yas; console.log(yas); — Correct. yas is declared but never given a value, so it is undefined.

  2. Assign null to pick

    let pick = ____;
    Show answer
    let pick = null;
  3. Match each value to its meaning

    undefined
    No value assigned
    null
    Intentional empty
    42
    A number
    true
    Logical true

All lessons in Beginner