Operators and Expressions

Course: JavaScript Beginner

Lesson 7: Operators and Expressions

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Use assignment, arithmetic, comparison, and logical operators correctly
  • Understand what an expression is and how JavaScript evaluates it to a value
  • Explain operator precedence and use parentheses to control evaluation order

Frontend Development Context

Every line of JavaScript that does something meaningful uses operators. Whether you are calculating a total, checking whether a user meets a condition, updating a counter, or building a string — all of these involve expressions made of operators and values. Understanding how operators work and in what order they evaluate is the difference between writing code that does what you intend and code that silently produces the wrong result.

Operator precedence is especially important in frontend work where conditions often combine multiple checks. A condition like age >= 18 && country === "US" || hasPermit means something specific — and without knowing precedence, you might not realize it means something different from what you intended.

Explanation

An expression is any piece of code that evaluates to a value. 5 + 3 is an expression that evaluates to 8. "hello".length is an expression that evaluates to 5. isLoggedIn && hasAccess is an expression that evaluates to a boolean. Expressions can be combined to form larger expressions.

Assignment operators set or update the value of a variable. The basic one is =. Shorthand operators combine assignment with arithmetic: += adds and assigns, -= subtracts and assigns, *= multiplies and assigns, ++ increments by one, -- decrements by one.

Arithmetic operators perform math: +, -, *, /, and % (modulo). The + operator is overloaded — it performs addition when both sides are numbers, and string concatenation when one or both sides are strings.

Comparison operators compare two values and return a boolean: === (strict equal), !== (strict not equal), >, <, >=, <=. Always prefer === over == to avoid unexpected type coercion.

Logical operators combine or invert boolean expressions: && (AND), || (OR), ! (NOT). These were covered in depth in the Booleans lesson — here the focus is on how they work within larger expressions and their precedence.

Operator precedence determines which operators evaluate first when an expression has multiple operators. The order (from highest to lowest priority for common operators) is roughly: parentheses (), then !, then *, /, %, then +, -, then >, <, >=, <=, then ===, !==, then &&, then ||. When in doubt, use parentheses to make your intent explicit.

Code Example

This example calculates a final cart total with a loyalty discount, using various operators:

let subtotal = 0;
const itemPrice = 12.99;
const itemCount = 4;
const loyaltyDiscount = 0.1; // 10%
const isMember = true;
const minimumForDiscount = 40;

subtotal += itemPrice * itemCount; // 51.96

// Only apply discount if member AND subtotal qualifies
const discountApplies = isMember && subtotal >= minimumForDiscount;
const discount = discountApplies ? subtotal * loyaltyDiscount : 0;
const total = subtotal - discount;

console.log(`Subtotal: $${subtotal.toFixed(2)}`);     // $51.96
console.log(`Discount: $${discount.toFixed(2)}`);     // $5.196
console.log(`Total: $${total.toFixed(2)}`);           // $46.76

Code Explanation

subtotal += itemPrice * itemCount demonstrates operator precedence in action. The multiplication * has higher precedence than +=, so itemPrice * itemCount evaluates to 51.96 first, and then that result is added to subtotal (which started at 0).

discountApplies is a compound boolean expression using &&. Both conditions must be true: the user must be a member AND the subtotal must be at least 40. If either is false, no discount applies.

The ternary operator discountApplies ? subtotal * loyaltyDiscount : 0 is a compact if/else expression. It reads: "if discountApplies is truthy, the discount is 10% of the subtotal; otherwise it is 0." This is an expression — it evaluates to a single value that gets stored in discount.

The += shorthand on the first line is equivalent to subtotal = subtotal + (itemPrice * itemCount). Shorthand operators like +=, -=, and *= are common in frontend code for updating counters, accumulating totals, and building strings incrementally.

Pattern Highlights

Positive Pattern: Use parentheses to make operator precedence explicit in complex expressions — (a + b) * c is clearer than relying on the reader knowing that * has higher precedence than +.

⚠️ Neutral Note: The ++ and -- operators (prefix vs postfix) behave differently: ++counter increments first and then returns the new value, while counter++ returns the current value first and then increments. In most cases, stick to counter += 1 for clarity.

Negative Pattern: Using == for equality comparisons allows type coercion: "5" == 5 is true, which is almost never what you intend. Always use ===.

Common Mistakes

Mistake 1: Misreading operator precedence in compound conditions

Without understanding precedence, mixed && and || conditions evaluate differently than expected.

// Intended: (isAdmin || isModerator) && isActive
const canEdit = isAdmin || isModerator && isActive;
// Actual evaluation: isAdmin || (isModerator && isActive)
// Because && has higher precedence than ||

If a user is an admin but not active, this returns true when you wanted false. Use parentheses to encode your intent explicitly: (isAdmin || isModerator) && isActive.

Mistake 2: Using = instead of === in a condition

Accidentally using a single = (assignment) instead of === (comparison) in an if condition assigns the value and always evaluates to truthy.

let status = "inactive";

if (status = "active") { // assigns "active" to status — always true!
  console.log("User is active"); // always runs, which is wrong
}

This is one of the most common beginner typos. Some developers write the literal first ("active" === status) as a guard against this, since you cannot accidentally assign to a literal.

Mistake 3: Forgetting that + concatenates when a string is involved

When one operand of + is a string, JavaScript converts the other to a string too and concatenates.

const count = 5;
const message = "You have " + count + 2 + " items";
// Result: "You have 52 items" — not "You have 7 items"
// Because "You have " + count gives "You have 5" (string),
// then "You have 5" + 2 gives "You have 52"

Use parentheses to force arithmetic: "You have " + (count + 2) + " items" gives the correct result. Better yet, use a template literal: `You have ${count + 2} items`.

Quick Recap

  • An expression is any piece of code that evaluates to a value — operators are what make expressions work
  • Assignment operators include =, +=, -=, *=, ++, and --
  • Comparison operators always use === (not ==) to avoid unexpected type coercion
  • Operator precedence determines evaluation order — use parentheses to make complex expressions unambiguous

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01