Operators and Expressions

Learn how to perform calculations, make comparisons, and combine values using JavaScript operators.

What are Operators?

// Operators perform operations on values
let sum = 10 + 5; // + is an operator
let isGreater = 10 > 5; // > is an operator
Operators work with values (operands)
sum → 15
isGreater → true

JavaScript has different types of operators for arithmetic, comparison, logical operations, and more.

Arithmetic Operators

let a = 10, b = 3;

console.log(a + b); // 13 (Addition)
console.log(a - b); // 7 (Subtraction)
console.log(a * b); // 30 (Multiplication)
console.log(a / b); // 3.33 (Division)
console.log(a % b); // 1 (Remainder)
console.log(a ** b); // 1000 (Exponentiation)
13
7
3.33
1
1000

Note: The remainder operator (%) returns division remainder.

Assignment Operators

let x = 5;
x += 3; // x = x + 3 → 8
x -= 2; // x = x - 2 → 6
x *= 4; // x = x * 4 → 24
x /= 3; // x = x / 3 → 8
x %= 5; // x = x % 5 → 3
Shorthand for common operations

These operators combine assignment with arithmetic operations for concise code.

Comparison Operators

console.log(5 == "5");  // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
console.log(10 > 5); // true
console.log(10 <= 10); // true
true
false
false
true
true
true

Best Practice: Always use strict equality (===) to avoid type coercion surprises.

Logical Operators

// AND (&&): Both must be true
console.log(true && true); // true
console.log(true && false); // false

// OR (||): At least one true
console.log(false || true); // true
console.log(false || false); // false

// NOT (!): Inverts boolean
console.log(!true); // false
console.log(!false); // true
true
false
true
false
false
true

Logical operators are often used with comparison operators in conditional statements.

String Operators

// Concatenation with +
let greeting = "Hello " + "World!";
console.log(greeting);

// Template literals (modern approach)
let name = "Alice";
let message = `Welcome ${name}!`;
console.log(message);
Hello World!
Welcome Alice!

Template literals (backticks) allow embedded expressions and multi-line strings.

Operator Precedence

// Multiplication before addition
let result = 2 + 3 * 4; // 14, not 20

// Use parentheses to control order
let withParens = (2 + 3) * 4; // 20

// Logical AND before OR
let logicalResult = true || false && false; // true
Operations have execution order:
Parentheses > Multiplication > Addition

When in doubt, use parentheses to make your intentions clear.

Expressions vs Statements

// Expression: Produces a value
3 * 5
x > 10
"Hello" + name

// Statement: Performs an action
let total = 3 * 5;
if (x > 10) { ... }
console.log("Hello");
Expressions evaluate to values
Statements perform actions

Expressions can be part of statements, but statements can't be part of expressions.

Common Operator Mistakes

// Confusing = with == or ===
if (x = 5) { ... } // ❌ Assignment, not comparison

// Type coercion surprises
console.log(1 + "1"); // "11" (not 2)
console.log("5" - 3); // 2 (number)

// Floating point precision
console.log(0.1 + 0.2); // 0.30000000000000004

Always use strict equality (===) and be cautious with type conversion in operations.

Practical Example: Shopping Cart

// Product prices
const shirtPrice = 25.99;
const pantsPrice = 39.99;
const taxRate = 0.08;

// User selections
let shirtQty = 2;
let pantsQty = 1;

// Calculations
let subtotal = (shirtPrice * shirtQty) + (pantsPrice * pantsQty);
let tax = subtotal * taxRate;
let total = subtotal + tax;

// Discount for orders over $50
let hasDiscount = total > 50;
if (hasDiscount) {
total *= 0.9; // 10% discount
}

// Display results
let output = document.getElementById("output");
output.innerHTML = `
Subtotal: $${subtotal.toFixed(2)}<br>
Tax: $${tax.toFixed(2)}<br>
Total: $${total.toFixed(2)} ${hasDiscount ? "(10% discount applied)" : ""}
`;
Subtotal: $91.97
Tax: $7.36
Total: $89.43 (10% discount applied)

Interactive Calculations

// Get buttons and add event listeners
document.getElementById("calcBtn").addEventListener("click", calculate);
document.getElementById("compareBtn").addEventListener("click", compare);
document.getElementById("logicBtn").addEventListener("click", logicalTest);

function calculate() {
let result = (20 * 3) + (15 / 3) - 4;
document.getElementById("output").textContent = `Result: ${result}`;
}

function compare() {
let comparison = 50 > (25 * 2) && "hello" === "hello";
document.getElementById("output").textContent = `Comparison: ${comparison}`;
}

function logicalTest() {
let logic = true || false && false;
document.getElementById("output").textContent = `Logical Test: ${logic}`;
}
Clicking "Calculate" shows: Result: 71
Clicking "Compare Values" shows: Comparison: true
Clicking "Logical Test" shows: Logical Test: true

Your Task: Interactive Operator Challenge

Make all three buttons functional by adding event listeners and implementing the required logic:

  1. Add an addEventListener to each button:
    • calcBtncalculate()
    • compareBtncompare()
    • logicBtnlogicalTest()
  2. Implement functions:
    • calculate(): Compute (10 + 5) * 2 and display result in the output div
    • compare(): Check if 10 * 2 is strictly equal to 20 and display boolean result
    • logicalTest(): Evaluate (5 > 3) || (2 < 1) and display boolean result
  3. Display results in this format:
    Calculation: 30
    Comparison: true
    Logical Test: true

Tip: Use different operators to see how values change

Challenge: Add a fourth button that combines all three operations in a single expression

Section 1/12What are Operators?

What are Operators?

JavaScript has different types of operators for arithmetic, comparison, logical operations, and more.

Operators and Expressions

Learn how to perform calculations, make comparisons, and combine values using JavaScript operators.

What are Operators?

// Operators perform operations on values
let sum = 10 + 5; // + is an operator
let isGreater = 10 > 5; // > is an operator
Operators work with values (operands)
sum → 15
isGreater → true

JavaScript has different types of operators for arithmetic, comparison, logical operations, and more.

Preview