Lesson 3 / 1030%

Lesson 3

Operators

16 min

Arithmetic, comparison and logical operators.

Definition

An operator is a symbol or keyword of the language that performs an operation on one or more values, calledoperands, and produces a result. For example, in the expression5 + 3, the symbol +is the operator, 5and 3are the operands, and 8is the result.

What are operators used for in JavaScript?

An operator is a symbol that lets you perform an operation on one or more values: adding two numbers, comparing two variables, combining several conditions... Operators are at the heart of the logic of every JavaScript program, whether it is to calculate a total price, validate a form or decide which content to show to the user.

There are generally three main families: arithmetic operators, comparison operators and logical operators.

An operator that works with two operands(a + b) is called binary. An operator that uses onlyone(!isActive,counter++) is called unary. Finally, there is one operator withthree operands, the ternary operator, which we will see later.

Arithmetic operators

They let you perform classic mathematical calculations on numbers.

arithmetic.js
const a = 10;
const b = 3;

a + b;  // 13       → addition
a - b;  // 7        → subtraction
a * b;  // 30       → multiplication
a / b;  // 3.333... → division
a % b;  // 1        → modulo (remainder of the integer division)
a ** b; // 1000     → exponentiation (a to the power of b)

The modulo (%) is particularly useful for checking whether a number is even or odd, or for creating repeating patterns (for example, a line every 5 values).

modulo.js
10 % 2; // 0 → 10 is even
7 % 2;  // 1 → 7 is odd

JavaScript also offers compound assignment operators, which simplify writing an operation followed by a reassignment:

compound-assignment.js
let total = 10;

total += 5;  // equivalent to: total = total + 5;  → 15
total -= 3;  // equivalent to: total = total - 3;  → 12
total *= 2;  // equivalent to: total = total * 2;  → 24
total /= 4;  // equivalent to: total = total / 4;  → 6

let counter = 0;
counter++; // increments by 1 → 1
counter--; // decrements by 1 → 0

Incrementing: before or after?

The ++operator can be placed before or afterthe variable. In both cases, the variable increases by 1, but the value returned by the expression is not the same.

pre-post-increment.js
let a = 5;
let b = a++; // b receives the old value (5), then a becomes 6

let c = 5;
let d = ++c; // c becomes 6, then d receives the new value (6)

console.log(a, b); // 6 5
console.log(c, d); // 6 6

The + operator with text: concatenation

The +operator leads a double life: between two numbers, it adds; as soon as one of the values is a string, it concatenates (it glues the texts end to end). The other arithmetic operators, on the other hand, try to convert the text into a number.

concatenation.js
"Hello " + "Léa"; // "Hello Léa" → concatenation
5 + 5;            // 10          → addition
"5" + 5;          // "55"        → concatenation!
"5" - 2;          // 3           → automatic conversion to a number
"abc" * 2;        // NaN         → conversion impossible

Operator precedence

As in mathematics, JavaScript does not always evaluate from left to right: some operators have priority. Multiplication and division come before addition and subtraction. To force an order, you useparentheses.

precedence.js
2 + 3 * 4;     // 14  → multiplication is done first
(2 + 3) * 4;   // 20  → parentheses come first
10 - 4 - 3;    // 3   → same priority: read from left to right
2 ** 3 ** 2;   // 512 → exponentiation is read from right to left

When in doubt, don't hesitate to add parentheses: they make the code more readable, even when they are not strictly necessary.

Comparison operators

They let you compare two values and always return aboolean (trueor false).

comparison.js
5 === 5;   // true  → strict equality (same value AND same type)
5 === "5"; // false → different types (number vs string)
5 == "5";  // true  → loose equality: JS converts the types before comparing
5 !== 3;   // true  → not equal (strict comparison)
5 != "5";  // false → not equal (loose comparison)
5 > 3;     // true  → greater than
5 < 3;     // false → less than
5 >= 5;    // true  → greater than or equal to
5 <= 4;    // false → less than or equal to
  • Always use === and !== rather than== and !=. Loose comparison can produce surprising results (for example, 0 == "" returnstrue).
  • Strings can also be compared with > and<: they are then compared in alphabetical order.

A few special cases to know

comparison-special-cases.js
"a" < "b";        // true  → "a" comes before "b" in the alphabet
"Z" < "a";        // true  → uppercase letters come before lowercase ones
"10" < "9";       // true  → text comparison: "1" comes before "9"
10 < 9;           // false → number comparison

NaN === NaN;      // false → NaN is not equal to anything, not even itself
[1] === [1];      // false → two distinct arrays are never "==="

The "10" < "9" trap shows why you must convert user input to numbers before comparing it: as long as it is text, the order is alphabetical, not numerical.

Logical operators

They let you combine several conditions together, which is essential for writing slightly more complex logic.

logic.js
const age = 20;
const hasLicense = true;

age >= 18 && hasLicense; // true  → logical AND: both conditions are true
age < 18 || !hasLicense; // false → logical OR: neither condition is true
!hasLicense;             // false → logical NOT: inverts the value
  • && (AND): returns true only if all conditions are true.
  • || (OR): returns true if at least one of the conditions is true.
  • ! (NOT): inverts a boolean value.

Truth tables

To memorize the behavior of&& and||, just try them with every possible combination of two booleans:

truth-tables.js
true && true;    // true
true && false;   // false
false && true;   // false
false && false;  // false   → AND: true only if EVERYTHING is true

true || true;    // true
true || false;   // true
false || true;   // true
false || false;  // false   → OR: false only if EVERYTHING is false

Short-circuit evaluation

JavaScript stops as soon as the result is known. With&&, if the first value is false, the second is not even evaluated. With||, if the first is true, it stops as well. This lets you write compact and safe checks.

short-circuit.js
const user = null;

// Without the "&&", user.name would cause an error
const name = user && user.name;
console.log(name); // null → reading .name never happened

A very common use case: giving a default value when a variable is empty, by combining||or the more modern??operator (nullish coalescing):

default-value.js
const username = "";
const displayName = username || "Guest"; // "Guest" (because username is an empty string)

const grade = 0;
const displayedGrade = grade ?? 10; // 0 (because 0 is neither null nor undefined)

The difference is important:||replaces any "falsy" value (0, "",false...), whereas??only replaces null and undefined. Use??when 0or an empty string are legitimate values.

The ternary operator: a condition on one line

The ternary operator is the only one with three operands. It evaluates a condition and returns one value if it is true, another if it is false. Its form is:condition ? valueIfTrue : valueIfFalse.

ternary.js
const age = 20;

const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

const message = age >= 18 ? "Access granted" : "Access denied";

It is very handy for choosing between two simple values. For longer logic, we will see theif / elsestructure in an upcoming lesson, which is more readable.

In practice: calculating the price of an order

The three families of operators combine naturally. In this example, we calculate a total, apply a discount and decide whether shipping is free:

order.js
const unitPrice = 12.5;
const quantity = 4;
const isLoyalCustomer = true;

// Arithmetic: the subtotal
let total = unitPrice * quantity; // 50

// Logic + arithmetic: 10% discount for loyal customers
if (isLoyalCustomer && total >= 40) {
  total = total * 0.9; // 45
}

// Comparison + ternary: free shipping from 40 onwards
const shipping = total >= 40 ? "free" : "paid";

console.log("Total:", total, "| Shipping:", shipping);
// Total: 45 | Shipping: free

You already recognize theifstructure here, which we will study in detail in the next lesson: it uses a condition built with the operators from this lesson.

The habit to adopt

When an expression looks doubtful, test it directly in the browser console: you will see its result immediately. It is the fastest way to understand operator precedence or the behavior of a comparison.

Common mistakes with operators

  • Mixing up = (assignment) and === (comparison): a very common mistake, especially in conditions.
  • Using == instead of ===, which can lead to bugs that are hard to spot.
  • Forgetting that addition with a string concatenates instead of adding: "5" + 5 returns "55", not 10.
  • Writing a double comparison as in mathematics: 0 < x < 10 does not work as expected; you must write x > 0 && x < 10.
  • Forgetting parentheses in a calculation and getting a different result because of operator precedence.

Exercise 1: calculations and comparisons

In a new JavaScript file:

  1. Declare two numeric variables of your choice.
  2. Display in the console the result of their addition, their multiplication and their modulo.
  3. Then display the result of the strict comparison "is the first variable greater than the second?".
  4. Use the && operator to check whether both numbers are positive.

Exercise 2: ternary operator and default value

Declare a variable grade containing a number between 0 and 20. Using a ternary operator, store in a variableresult the text "passed" if the grade is greater than or equal to 10, and "failed" otherwise. Then display a complete sentence in the console.

Bonus: declare nickname = "" and displaynickname || "No nickname", then explain whynickname ?? "No nickname" gives a different result.

Key takeaways

  • An operator acts on operands to produce a result.
  • Arithmetic operators (+, -, *, /, %) are used for calculations, and parentheses let you control their order.
  • Comparison operators always return a boolean: always prefer === and !==.
  • Logical operators (&&, ||, !) let you combine conditions and are evaluated with short-circuiting.
  • ?? provides a default value only for null and undefined, whereas || replaces any falsy value.
  • The ternary operator condition ? a : b chooses between two values on a single line.
  • As soon as text is involved, + concatenates instead of adding: convert your values with Number() if needed.
  • When in doubt about a result, test the expression in the browser console.