Codiqo

Learn JavaScript · lesson 10 of 60 · about 7 minutes

Equality, null and undefined

Ask visitors for their favourite language: compare it safely with ===, and handle the visitor who skips the question.

What you'll learn

  • Compare with === and !==
  • Tell null from undefined
  • Give a fallback with ??

Strict equality

=== checks that two values are the same and the same type, and gives true or false. !== asks the opposite: are they different?

The older == converts types before comparing, so "5" == 5 is true. That hides bugs, so use === every time. And never =: one equals sign stores a value, it doesn't compare.

=== versus ==

console.log(5 === 5);
console.log("5" === 5);
console.log("5" == 5);
console.log("JavaScript" !== "Python");

Output

true
false
true
true

Two kinds of nothing

  • undefined means no value was ever given, like a variable declared without one
  • null means empty on purpose: a visitor who skipped the favourite-language question gives null

?? gives a fallback when a value is null or undefined: fav ?? "not chosen yet". Unlike ||, it keeps real values like 0 and "".

null, undefined and ??

let nickname;
console.log(nickname);
const fav = null;
console.log(fav ?? "not chosen yet");
console.log(0 ?? 5, 0 || 5);

Output

undefined
not chosen yet
0 5

Tip

typeof null is "object". It's a famous old mistake in JavaScript that can't be fixed without breaking websites.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.