JavaScript • Syntax and Core Types

Arithmetic & Comparison Operators — Use arithmetic and comparison operators

Master the symbols that let JavaScript perform math and make decisions in your code.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 9 figures

SECTION 1

Historical Context & Motivation

Every programming language needs a way to do math and compare values. Long before JavaScript existed, mathematicians and early computer scientists developed the operator concept — a symbol that tells the computer to perform a specific action on one or more values. When Brendan Eich created JavaScript in 1995, he borrowed operator syntax from the C programming language, which itself drew from mathematical notation developed over centuries.

Understanding this history helps explain why JavaScript uses symbols like === instead of a simple equals sign, and why % means "remainder" rather than "percent." These design choices trace back through decades of programming language evolution.

1600s • Mathematical Notation Emerges

Robert Recorde invents the equals sign (=) and mathematicians standardize +, −, ×, and ÷ for arithmetic, laying the foundation for all future operator symbols.

1957 • FORTRAN Introduces Operators

FORTRAN, one of the first high-level programming languages, uses symbols like + and - and comparison operators like .EQ. and .GT. in compiled programs.

1972 • C Language Sets the Standard

Dennis Ritchie's C language establishes the operator syntax that most modern languages follow, including == for equality and % for the modulus (remainder) operation.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in just 10 days. He adopts C-style operators but adds === (strict equality) to handle JavaScript's unique type coercion behavior.

2016 • ES2016 Adds the Exponentiation Operator

ECMAScript 2016 introduces ** as a shorthand for raising a number to a power, replacing the need to call Math.pow().

Today, arithmetic and comparison operators are the fundamental building blocks of every JavaScript program. Whether you're calculating a score in a game, validating a user's age, or sorting a list of items, you'll rely on these operators constantly. The question this lesson addresses is straightforward: how do you use operators to perform calculations and make comparisons in JavaScript?

SECTION 2

Core Principles & Definitions

Before diving into each operator, you need to understand a few foundational ideas. An operator is a special symbol that performs an operation on values (called operands). In the expression 5 + 3, the + is the operator and 5 and 3 are the operands. The entire thing is called an expression, and it evaluates (resolves) to a single value — in this case, 8.

1

Arithmetic Operators

Perform math calculations: + (add), - (subtract), * (multiply), / (divide), % (remainder), ** (exponent). These always return a number.
2

Comparison Operators

Compare two values and return true or false. Includes >, <, >=, <=, ==, ===, !=, and !==.
3

Operator Precedence

JavaScript follows math rules for order of operations (like PEMDAS). Exponents evaluate before multiplication and division, which evaluate before addition and subtraction. Parentheses override this order.
4

Type Coercion

JavaScript may secretly convert data types during operations. For example, "5" - 2 gives 3 (string becomes number), but "5" + 2 gives "52" (concatenation). This is a common gotcha!
5

Strict vs. Loose Equality

Use === (strict) to compare both value and type. Use == (loose) to compare values after type coercion. Best practice is to always use === to avoid unexpected behavior.
✦

KEY TAKEAWAY

Think of operators like tools in a toolbox. Arithmetic operators are like a calculator — they crunch numbers and give you a result. Comparison operators are like a judge at a contest — they look at two values and announce a verdict of true or false. Together, they give your programs the ability to compute and decide.

SECTION 3

Visual Explanation — The Operator Family Tree

The diagram below maps out every arithmetic and comparison operator you'll use in JavaScript. The left branch shows arithmetic operators that produce numeric results, while the right branch shows comparison operators that always return a Boolean (true or false) value.

JavaScript Operatorsexpression → valueArithmetic OperatorsComparison Operators+Addition5 + 3 → 8−Subtraction10 − 4 → 6*Multiplication6 * 7 → 42/Division20 / 4 → 5%Remainder17 % 5 → 2**Exponentiation2 ** 3 → 8Returns: Number===Strict Equal!==Strict Not Equal==Loose Equal!=Loose Not Equal>Greater Than<Less Than>= <=Greater/Less or EqualReturns: Boolean (true / false)
The operator family tree shows two branches. The arithmetic branch (left, cyan) always produces a number, while the comparison branch (right, violet) always produces a Boolean. Notice how strict equality (===) appears above loose equality (==) — that's because strict equality is the recommended default.

As you can see in the diagram, the critical distinction is what each family of operators returns. Arithmetic operators produce a numeric result, while comparison operators produce a Boolean result. This matters because you'll use arithmetic operators to calculate values (like a total price) and comparison operators to make decisions (like checking if a user is old enough to register).

SECTION 4

How Operators Work Under the Hood

Arithmetic Operators in Detail

JavaScript's arithmetic operators follow the same order of operations you learned in math class. The acronym PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) applies directly. The modulus operator (%) shares the same precedence level as multiplication and division.

ORDER OF OPERATIONS

()→∗∗→∗/( ) → ** → * / % → + −

Parentheses are evaluated first, then exponentiation, then multiplication/division/remainder (left to right), and finally addition/subtraction (left to right).

MODULUS (REMAINDER)

aa % b = a − b × floor(a ÷ b)

The % operator returns the remainder after dividing a by b. For example, 17 % 5 = 17 − 5 × 3 = 17 − 15 = 2.

Comparison Operators in Detail

Comparison operators evaluate an expression and always return true or false. The most important distinction is between strict equality (===) and loose equality (==). Strict equality checks both the value and the data type, while loose equality converts types before comparing.

STRICT EQUALITY

5==="5"→false(number≠stringtype)5 === "5" → false (number ≠ string type)

The === operator asks: "Are these the same value AND the same type?" Since 5 is a number and "5" is a string, the answer is false.

LOOSE EQUALITY

5=="5"→true(stringcoercedtonumberfirst)5 == "5" → true (string coerced to number first)

The == operator first converts "5" to the number 5, then compares. Since both are now 5, the result is true. This hidden conversion is called type coercion and is a common source of bugs.

💡

Pro Tip

Always use === and !== unless you have a specific reason to use loose equality. This single habit will prevent a huge number of bugs in your code. Professional JavaScript style guides (like Airbnb's) enforce this rule.

SECTION 5

Operator Reference Table & Type Coercion Flow

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
%Remainder (modulus)10 % 31
**Exponentiation2 ** 416
===Strict equal5 === 5true
!==Strict not equal5 !== "5"true
>Greater than10 > 3true
<=Less than or equal5 <= 5true

JavaScript Arithmetic & Comparison Operators Quick Reference

One of the trickiest aspects of JavaScript operators is how the + operator behaves differently depending on the types of its operands. When both operands are numbers, + performs addition. But when one operand is a string, JavaScript converts the other operand to a string and performs concatenation (joining) instead. The diagram below illustrates this decision process.

How the + Operator Decides: Add or Concatenate?a + bIs either operand a string?NOYESNumeric Addition5 + 3 → 8String Concatenation"5" + 3 → "53"typeof result → "number"typeof result → "string"⚠ The other arithmetic operators (−, *, /, %, **) always convert to numbers
This flowchart shows the decision JavaScript makes when it encounters the + operator. If either operand is a string, the result is string concatenation. Otherwise, JavaScript performs numeric addition. Note the amber warning at the bottom: all other arithmetic operators always convert to numbers.
⚠

Common Gotcha

When you read input from an HTML form or prompt box, the value is always a string — even if the user typed a number. Writing prompt('Enter a number:') + 5 when the user types 10 gives "105" (string concatenation), not 15. Use Number() or parseInt() to convert first.

SECTION 6

Worked Example — Building a Grade Calculator

Let's walk through a realistic example that uses both arithmetic and comparison operators. Imagine you're writing a program that calculates a student's final grade percentage and determines their letter grade.

Grade Calculator

  1. 1

    Step 1 — Define the Scores

    We have three test scores stored in variables. We'll use these throughout the calculation. let test1 = 85; let test2 = 92; let test3 = 78;
    Three variables holding numeric scores: 85, 92, and 78.
  2. 2

    Step 2 — Calculate the Average (Arithmetic Operators)

    To find the average, we add all three scores and divide by 3. Notice we use parentheses to ensure addition happens before division. let average = (test1 + test2 + test3) / 3; Without parentheses, test1 + test2 + test3 / 3 would divide only test3 by 3 first (operator precedence), giving the wrong answer.
    average = (85 + 92 + 78) / 3 = 255 / 3 = 85
  3. 3

    Step 3 — Check for Bonus Points (Comparison + Arithmetic)

    If all scores are above 75, the student gets 2 bonus points. We use comparison operators to check. let allAbove75 = (test1 > 75) && (test2 > 75) && (test3 > 75); Each comparison (test1 > 75) returns true or false. All three are true here, so allAbove75 is true.
    allAbove75 = true → Student earns +2 bonus → average = 85 + 2 = 87
  4. 4

    Step 4 — Determine Letter Grade (Comparison Operators)

    Now we use comparison operators to assign a letter grade based on the final average. let grade; if (average >= 90) { grade = "A"; } else if (average >= 80) { grade = "B"; } else if (average >= 70) { grade = "C"; } else { grade = "F"; } Since 87 >= 90 is false, JavaScript moves to the next check: 87 >= 80 is true.
    Final grade: B (average of 87)
  5. 5

    Step 5 — Verify with Strict Equality

    We can verify our result using strict equality. console.log(grade === "B"); // true console.log(average === 87); // true console.log(typeof average === "number"); // true Using === confirms both the value and the type match exactly.
    All checks pass. The grade is confirmed as "B" and the average is a number with value 87.

SECTION 7

Strengths, Limitations & Common Pitfalls

JavaScript's operators are powerful but come with some quirks that can catch you off guard. The table below compares key strengths and limitations you should be aware of as you write code.

FeatureStrengthLimitation / Pitfall
Arithmetic operatorsFamiliar math symbols make code readable. The ** operator is cleaner than Math.pow().Floating-point precision issues: 0.1 + 0.2 gives 0.30000000000000004, not 0.3.
The + operatorWorks for both addition and string joining, which is convenient for building messages.Dual behavior (add vs. concatenate) is the #1 source of JavaScript bugs for beginners.
Strict equality (===)No hidden type conversion — what you see is what you get. Predictable and safe.Cannot compare object contents. [1] === [1] is false because they're different objects in memory.
Loose equality (==)Occasionally useful for checking null == undefined (both return true).Unpredictable coercion rules: "" == 0 is true, and "0" == false is also true.
Modulus operator (%)Perfect for checking even/odd numbers, cycling through arrays, and clock arithmetic.Behaves unexpectedly with negative numbers: -7 % 3 gives -1, not 2.

Strengths and Limitations of JavaScript Operators

✦

KEY TAKEAWAY

Think of type coercion like an overly helpful friend who "translates" your words but sometimes gets the meaning wrong. When you say "5" + 3, JavaScript "helps" by treating everything as a string. Using strict equality (===) is like telling JavaScript: "Don't translate — compare exactly what I gave you." This is almost always what you want.

SECTION 8

Connection to Advanced Concepts

The arithmetic and comparison operators you've learned here are stepping stones to more advanced JavaScript concepts. As you grow as a developer, you'll encounter operators and patterns that build directly on this foundation.

What You Know NowWhat Comes NextHow They Connect
+, -, *, /Assignment operators: +=, -=, *=, /=Shorthand for x = x + 5 → x += 5. Combines arithmetic with variable assignment.
Comparison operators (>, <, ===)Logical operators: &&, ||, !Combine multiple comparisons: age >= 13 && age <= 19 checks if someone is a teenager.
Expressions returning valuesTernary operator: condition ? a : bA compact way to choose between two values based on a comparison, like a mini if-else.
Type coercion awarenessTypeScript and type checkingTypeScript adds static types to JavaScript, catching coercion bugs before your code even runs.
% (modulus)Bitwise operators: &, |, ^, ~, <<, >>Operate on the binary (bit-level) representation of numbers. Used in graphics, cryptography, and performance optimization.

From Basic Operators to Advanced Concepts

As you continue learning JavaScript, you'll find that operators combine like building blocks. A conditional statement like if (score >= 60 && attempts < 3) mixes comparison operators with logical operators, which in turn rely on your understanding of what >= and < return. Every advanced pattern traces back to the fundamentals covered in this lesson.

SECTION 9

Practice Problems

Test your understanding with these five problems. They escalate in difficulty from simple recall to critical thinking about operator behavior.

Question 1: CONCEPTUAL

What is the key difference between == and === in JavaScript? Why do most style guides recommend ===?
Show answer
The == (loose equality) operator compares values after performing type coercion, meaning JavaScript converts the operands to the same type before comparing. The === (strict equality) operator compares both the value and the type with no conversion. For example, 5 == "5" is true but 5 === "5" is false. Style guides recommend === because it eliminates surprises caused by hidden type conversion, making your code more predictable and less bug-prone.

Question 2: BASIC CALCULATION

What does each of the following expressions evaluate to? (a) 15 % 4 (b) 2 ** 5 (c) 10 + 3 * 2 (d) (10 + 3) * 2
Show answer
(a) 15 % 4 evaluates to 3 because 15 ÷ 4 = 3 remainder 3. (b) 2 ** 5 evaluates to 32 because 2⁵ = 32. (c) 10 + 3 * 2 evaluates to 16 because multiplication has higher precedence than addition, so 3 × 2 = 6 is calculated first, then 10 + 6 = 16. (d) (10 + 3) * 2 evaluates to 26 because parentheses force addition first: 13 × 2 = 26.

Question 3: INTERMEDIATE

Predict the output of each expression and explain why: (a) "10" + 5 (b) "10" - 5 (c) true + 1 (d) null == undefined
Show answer
(a) "105" — the + operator sees a string on the left, so it concatenates instead of adding. (b) 5 — the - operator only does math, so it converts "10" to the number 10, then subtracts. (c) 2 — JavaScript coerces true to 1 in arithmetic, so 1 + 1 = 2. (d) true — this is a special rule in JavaScript: null and undefined are considered loosely equal to each other (but not to anything else).

Question 4: APPLIED

You're building an online store. Write a JavaScript expression that calculates the final price of an item that costs $49.99 with a 15% discount, then checks if the discounted price is under $45. Use the variables price = 49.99 and discount = 0.15. What does each expression evaluate to?
Show answer
First, calculate the discounted price: let finalPrice = price - (price * discount); which is 49.99 - (49.99 * 0.15) = 49.99 - 7.4985 = 42.4915. Then check if it's under $45: let isUnder45 = finalPrice < 45; which evaluates to true since 42.4915 < 45. Note that the parentheses around price * discount aren't strictly necessary (multiplication happens before subtraction), but they improve readability.

Question 5: CRITICAL THINKING

A classmate writes the following code to check if a year is a leap year. It doesn't work correctly for all cases. Identify the bug and rewrite the condition using arithmetic and comparison operators. let isLeap = (year % 4 == 0); Hint: A year is a leap year if it is divisible by 4, EXCEPT century years (divisible by 100) must also be divisible by 400.
Show answer
The bug is that the original code only checks divisibility by 4, but the leap year rule is more complex. The year 1900 is divisible by 4 but is NOT a leap year because it's a century year not divisible by 400. The corrected code is: let isLeap = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0); This uses the modulus operator (%) to check divisibility, strict equality (!==, ===) for comparisons, and logical operators (&&, ||) to combine conditions. For year = 2000: 2000 % 400 === 0 is true, so it's a leap year. For year = 1900: 1900 % 4 === 0 is true but 1900 % 100 !== 0 is false, and 1900 % 400 === 0 is false, so it's correctly identified as not a leap year.

SUMMARY

Lesson Summary

Summary

JavaScript provides two families of operators that form the backbone of every program. Arithmetic operators (+, -, *, /, %, **) perform calculations and always return a number. Comparison operators (===, !==, >, <, >=, <=) evaluate relationships between values and always return a Boolean (true or false). JavaScript follows standard operator precedence (PEMDAS), and parentheses can override the default order.

The most important best practice is to always use strict equality (===) instead of loose equality (==) to avoid unexpected type coercion. Watch out for the + operator's dual behavior — it adds numbers but concatenates strings. The modulus operator (%) is especially useful for checking even/odd numbers and cyclic patterns. Master these operators, and you'll have the foundation for every conditional statement, loop, and function you'll ever write in JavaScript.

Varsity Tutors • JavaScript • Arithmetic & Comparison Operators