Computer Programming 1 (JavaScript) • Environment, Syntax & Types

Operators & == vs. === — I can use arithmetic and comparison operators and explain the difference between == and === at a basic level.

Master the symbols JavaScript uses to do math, compare values, and avoid subtle equality bugs.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Every programming language needs a way to perform calculations and make decisions. From the earliest mechanical calculators to modern web browsers, operators are the fundamental symbols that tell a computer what to do with data. When Brendan Eich created JavaScript in just ten days in 1995, he borrowed operator syntax from the C programming language family but added a twist: a loose equality operator (==) that tries to be "helpful" by automatically converting types before comparing. This design choice caused so many bugs over the years that the language eventually added a strict equality operator (===) to fix the problem.

1972 • C Language Introduces Familiar Operators

Dennis Ritchie's C language established the arithmetic operators (+, −, ×, /) and the single == for equality that almost every modern language still uses.

1995 • JavaScript Is Born

Brendan Eich created JavaScript for Netscape Navigator. He included == as a loose equality check that performs automatic type conversion, called type coercion.

1999 • ECMAScript 3 Adds ===

The third edition of the ECMAScript standard formalized === (strict equality) so developers could compare values without unexpected type conversions.

2015 • ES6 & Modern Best Practices

Modern JavaScript style guides (like Airbnb and Google) universally recommend using === by default to prevent subtle bugs.

Understanding operators is essential because nearly every line of JavaScript involves at least one. Whether you are calculating a game score, checking if a password matches, or deciding which branch of code to run, you need arithmetic and comparison operators. The central question of this lesson is: how does JavaScript evaluate math, and why does the way you compare values matter so much?

SECTION 2

Core Principles & Definitions

Before diving into code, let's nail down the vocabulary. An operator is a special symbol that performs an action on one or more values (called operands). JavaScript groups operators into several families. In this lesson we focus on two: arithmetic operators (for math) and comparison operators (for making decisions).

1

Arithmetic Operators

Symbols that perform math: + (add), - (subtract), * (multiply), / (divide), % (remainder), and ** (exponent).
2

Comparison Operators

Symbols that compare two values and return true or false: >, <, >=, <=, ==, ===.
3

Type Coercion

When JavaScript automatically converts a value from one type (like a string) to another (like a number) so it can perform an operation. This is the root cause of the == vs. === issue.
4

Operand & Expression

An operand is any value an operator acts on. An expression is a combination of values and operators that evaluates to a single result. For example, 3 + 5 is an expression where 3 and 5 are operands.
✦

KEY TAKEAWAY

Think of operators like buttons on a calculator. Arithmetic operators are the basic math buttons (+, −, ×, ÷). Comparison operators are like a judge at a talent show: they look at two contestants and declare true or false. The difference between == and === is like comparing two students: == asks "do they look similar after changing outfits?" while === asks "are they the exact same person wearing the exact same outfit?"

SECTION 3

Visual Explanation — Arithmetic Operators in Action

JavaScript Arithmetic Operators+ Addition10 + 3 → 13- Subtraction10 - 3 → 7* Multiplication10 * 3 → 30/ Division10 / 3 → 3.333…% Remainder10 % 3 → 1** Exponent10 ** 3 → 1000Order of Operations (like PEMDAS)( )→**→* / %→+ -Highest priority on the left → Lowest priority on the rightExample: 2 + 3 * 4 → 2 + 12 → 14 (multiplication before addition)
The six arithmetic operators in JavaScript, each with an example. Below them, the order of operations shows which operators are evaluated first — just like PEMDAS in math class.

As you can see in the diagram, JavaScript follows the same order of operations you learned in algebra. Parentheses come first, then exponents (**), then multiplication, division, and remainder (* / %), and finally addition and subtraction (+ -). The remainder operator (%), also called modulo, returns the leftover after integer division. For instance, 10 % 3 gives 1 because 10 ÷ 3 = 3 remainder 1. This operator is incredibly useful for things like checking whether a number is even or odd.

SECTION 4

How == and === Actually Work

This is where things get interesting — and where many beginners trip up. JavaScript has two ways to check if values are equal, and they behave very differently under the hood.

Loose Equality: ==

The loose equality operator (==) compares two values after attempting to convert them to the same type. If you compare the number 5 with the string "5", JavaScript converts the string to a number behind the scenes, then compares. The result? 5 == "5" returns true. This automatic conversion is called type coercion.

Strict Equality: ===

The strict equality operator (===) checks both the value and the type without any conversion. If the types don't match, it immediately returns false. So 5 === "5" returns false because a number is not the same type as a string, even though they look the same to a human.

== vs. === Decision FlowchartCompare: 5 and "5"== path=== pathStep 1: Are types the same?number ≠ string → NoStep 1: Are types the same?number ≠ string → NoStep 2: Coerce types!"5" → 5 (convert string)Step 2: STOPTypes differ → return falseStep 3: Compare values5 == 5 → truetrue5 == "5"false5 === "5"=== never coerces — if types differ, the answer is immediately false
This flowchart traces how == and === each handle the comparison 5 vs. "5". Notice how == converts the string to a number before comparing, while === stops as soon as it sees different types.
⚠

Common Gotcha

A single = is the assignment operator — it stores a value in a variable. Double == and triple === are for comparison. Mixing them up is one of the most common bugs for beginners!

SECTION 5

Detailed Breakdown of Comparison Operators

Beyond equality checks, JavaScript provides several operators for comparing relative size. Each returns a Boolean value — either true or false. These are essential for making decisions in your code with if statements, loops, and more.

OperatorNameExampleResult
>Greater than10 > 3true
<Less than10 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to4 <= 3false
==Loose equality (coerces types)5 == "5"true
===Strict equality (no coercion)5 === "5"false
!=Loose not-equal5 != "5"false
!==Strict not-equal5 !== "5"true

All JavaScript comparison operators at a glance

Notice the pattern: just as == has a strict partner ===, the not-equal operator != has a strict partner !==. The strict versions always avoid type coercion, making your code more predictable. Most professional JavaScript developers use === and !== almost exclusively.

ℹ

Surprising Coercion Examples

Type coercion with == can produce some truly unexpected results: "" == 0 is true, null == undefined is true, and false == "0" is true. These are the kinds of bugs that === prevents!

SECTION 6

Worked Example — Building a Score Checker

Let's walk through a realistic scenario. Imagine you are building a simple game where the player needs a score of at least 100 to pass a level. The player's score comes from a text input on a web page, so it arrives as a string.

Does the Player Pass the Level?

  1. 1

    Step 1 — Identify the Variables

    The player's score comes from an input field and is stored as a string. We write: let playerScore = "120"; and the passing threshold is let passingScore = 100; (a number).
    playerScore is a string, passingScore is a number
  2. 2

    Step 2 — Calculate Bonus Points with Arithmetic

    The player earned a 10% bonus. We first convert the string to a number, then calculate: let numericScore = Number(playerScore); gives us 120. Then let bonus = numericScore * 0.10; gives us 12. Finally, let finalScore = numericScore + bonus; gives the total.
    finalScore = 132
  3. 3

    Step 3 — Compare Using >=

    To check if the player passes, we use the comparison operator: finalScore >= passingScore evaluates to 132 >= 100.
    true — the player passes!
  4. 4

    Step 4 — Show the Danger of ==

    Now imagine we check playerScore == 120 without converting first. Because == coerces the string "120" to the number 120, this returns true. But playerScore === 120 returns false because the types don't match. This shows why you should always convert types explicitly and use ===.
    "120" == 120 → true but "120" === 120 → false

SECTION 7

== vs. === — Strengths & Limitations

Now that you understand both operators, let's compare them side by side so you can make an informed decision about which to use.

Feature== (Loose Equality)=== (Strict Equality)
Type coercion?Yes — converts types before comparingNo — types must already match
5 vs. "5"truefalse
null vs. undefinedtruefalse
PredictabilityLow — coercion rules are complexHigh — no surprises
Bug riskHigher — silent type conversionsLower — fails fast if types differ
Best practice?Rarely recommendedIndustry standard

Side-by-side comparison of loose vs. strict equality

✦

KEY TAKEAWAY

Think of == like a spell-checker that auto-corrects your words before checking if they match — sometimes helpful, but often changes your meaning in unexpected ways. === is like a strict teacher who checks your exact spelling, no auto-correct allowed. In professional JavaScript, === is the default choice because you always know exactly what you're comparing.

SECTION 8

Connection to Advanced Concepts

The operators you have learned here are the building blocks for more advanced topics in JavaScript. As you continue, you will encounter logical operators (&&, ||, !) that combine comparison results, ternary operators for shorthand conditionals, and methods like Object.is() for even more precise equality checks.

This LessonComing Next
Arithmetic: + - * / % **Assignment shortcuts: += -= *= /=
Comparison: > < >= <= == ===Logical: && || ! for combining conditions
Manual type conversion with Number()Understanding truthy/falsy values and implicit coercion
Single comparisons returning true / falseUsing comparisons inside if / else blocks to control program flow

How today's operators connect to future topics

Mastering arithmetic and comparison operators now gives you a solid foundation. Every conditional statement, every loop, and every function you write in JavaScript will rely on the skills you practiced in this lesson. The distinction between == and === is not just a trivia question — it is a real-world habit that separates reliable code from buggy code.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain the difference between == and === in JavaScript. Why do most professional developers prefer ===?
Show answer
The == operator (loose equality) converts both values to the same type before comparing them, which can produce unexpected results. The === operator (strict equality) checks both the value and the type without any conversion. If the types don't match, it immediately returns false. Professional developers prefer === because it is more predictable — you always know exactly what is being compared, and you avoid subtle bugs caused by type coercion.

Question 2: BASIC CALCULATION

What does each expression evaluate to? Write the answer next to each one. 15 % 4 2 ** 5 10 + 3 * 2 (10 + 3) * 2
Show answer
15 % 4 → 3 (15 ÷ 4 = 3 remainder 3). 2 ** 5 → 32 (2 raised to the 5th power). 10 + 3 * 2 → 16 (multiplication happens first: 3 × 2 = 6, then 10 + 6 = 16). (10 + 3) * 2 → 26 (parentheses force addition first: 13 × 2 = 26).

Question 3: INTERMEDIATE

Predict the result (true or false) for each comparison, and explain why: 0 == false 0 === false "" == false null === undefined
Show answer
0 == false → true because == converts false to 0, and 0 equals 0. 0 === false → false because a number and a boolean are different types, so strict equality fails immediately. "" == false → true because both an empty string and false convert to 0 during coercion. null === undefined → false because they are technically different types (null is type 'object', undefined is type 'undefined'), so strict equality returns false even though null == undefined would return true.

Question 4: APPLIED

You are writing a tip calculator. The meal cost is $48.50 and the tip percentage is 20%. Write JavaScript expressions to: (a) calculate the tip amount, (b) calculate the total bill, and (c) check whether the total bill is strictly equal to the number 58.2. What will expression (c) return and why?
Show answer
(a) let tipAmount = 48.50 * 0.20; which gives 9.7. (b) let totalBill = 48.50 + tipAmount; which gives 58.2. (c) totalBill === 58.2 returns true because both values are numbers and have the same value. Note: in some floating-point edge cases, JavaScript math can produce tiny rounding errors (e.g., 0.1 + 0.2 gives 0.30000000000000004), so in more complex calculations you should be aware of this limitation.

Question 5: CRITICAL THINKING

A student writes the following code and says it works fine: let userAge = prompt("Enter your age:"); if (userAge == 18) { console.log("You can vote!"); } Explain why this code could be considered problematic. Rewrite it using best practices so it works correctly and safely.
Show answer
The prompt() function always returns a string, so userAge is "18" (a string), not 18 (a number). Using == happens to work here because loose equality coerces the string to a number, but this masks a type mismatch. If the code later uses userAge in arithmetic (e.g., userAge + 1), it would concatenate strings instead of adding numbers, producing "181" instead of 19. Best practice: explicitly convert the type and use strict equality: let userAge = Number(prompt("Enter your age:")); if (userAge === 18) { console.log("You can vote!"); } This approach is clearer, avoids hidden coercion, and prevents downstream bugs.

SUMMARY

Lesson Summary

Summary

JavaScript provides six arithmetic operators — +, -, *, /, % (remainder), and ** (exponent) — that follow the same order of operations you already know from math class (PEMDAS). Comparison operators like >, <, >=, and <= return true or false, enabling your programs to make decisions.

The most critical distinction in this lesson is between loose equality (==), which performs type coercion before comparing, and strict equality (===), which checks both value and type with no conversion. Always use === by default to write predictable, bug-resistant code. Convert types explicitly with functions like Number() when you need them to match.

Varsity Tutors • Computer Programming 1 (JavaScript) • Operators & == vs. ===