Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Equality Comparisons  ›  Lesson

Loose Equality (==)

== 12 minLoose equality converts values of different types, mostly towards numbers, before comparing, while null and undefined equal only each other.

Loose Equality (==)

In short: == converts values before comparing them, and its conversion rules are one of the language's most famous sources of surprise. When the types already match, == behaves exactly like ===. When they differ, it slides values towards a number: a boolean becomes 0 or 1, a string becomes a number, an object becomes a primitive first. The one exception is null and undefined: they equal each other and nothing else, with no conversion at all. Most style guides say: default to ===, and keep == only for the one useful idiom value == null.

[] == false traced in four steps: false → 0, giving [] == 0; the empty array converts to "" giving "" == 0; "" converts to 0 giving 0 == 0 → true — with a note that an empty array "equals" false even though [] is truthy in an if, and that null/undefined are never converted

Compare a form value to a number

A value read from a search box or URL arrives as a string, even when it looks numeric:

javascript

"2" == 2 is true — the string converts to the number 2 first. null == undefined is true by the special rule that exempts them from conversion. But null == 0 is false: null is never converted to a number, so it only ever matches undefined (and itself) under ==. And "true" == true is false — true becomes the number 1, but the string "true" converts to NaN, which equals nothing.

Trace an empty array against false

An object meets ==, and the object is converted to a primitive before the usual number rules apply — which produces one of the language's strangest results:

javascript

This is true. Step by step: false becomes 0 (rule for booleans), the empty array becomes "" (arrays convert to their items joined by commas — an empty array joins to nothing), then "" becomes 0, and 0 == 0 is true. Yet inside an if, [] is truthy — if ([]) { ... } runs its block. == and truthiness follow completely different rules, and this is exactly why they can disagree.

Evaluating [] == falseStep 1 of 4
  1. Boolean first

    false becomes 0. Now: [] == 0.

Quick practice

quick drill

What is "5" == 5?

quick drill

What is null == 0?

quick drill

What is "" == 0?

quick drill

What is "true" == true?

quick drill

What is [] == false?

🎯 Your turn

Trace "0" == false step by step and explain the result. Then explain why if ("0") still runs its block, and what that says about using ==.

Write your explanation and submit it — there's no code to run here, just your reasoning.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainTrace the conversions

Trace "0" == false step by step and explain the result. Then explain why if ("0") still runs its block, and what that says about using ==.