ProgramGuru

Equality Operators

Learn Equality Operators

Equality compares whether two values are the same. Strict equality avoids implicit type coercion.

In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.

What you’ll learn

  • Explain the main rule behind equality operators.
  • Predict the result of the complete runnable TypeScript example.
  • Recognize one common mistake and correct it.

Understand the concept

Prefer === and !==. Loose equality (== and !=) performs coercion in some cases, giving results that can surprise beginners. Objects are compared by reference identity, not by recursively comparing their fields.

Run a complete TypeScript example

Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.

TypeScript code

const code: number = 5;
 const text: string = "5";
 console.log(code === Number(text));
 console.log(code === 6);
 const first = { x: 1 };
 const second = { x: 1 };
 console.log(first === second);

Verified output

true
false
false

How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.

Trace the execution

Explicitly parsing "5" gives the number 5, so the first comparison is true. The second is false. Two separately created objects have different references, so the third is false.

Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.

Common mistakes and how to avoid them

Do not use == casually with mixed input types or assume two separately constructed objects are equal because their fields match.

Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.

Practice it yourself

Create one object in a variable, copy its reference to another variable, then compare them with ===.

Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.

Check your understanding

What does === compare for two objects?
Choose one answer. You can try again.

Answer and explanation

Whether the references identify the same object.

Strict equality uses identity for objects; it does not perform deep comparison.

Review the key idea

Equality Operators: Prefer === and !==.

Strict equality uses identity for objects; it does not perform deep comparison.

Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Optional Chaining →