Operators and Expressions
Learn how to perform calculations, make comparisons, and combine values using JavaScript operators.
What are Operators?
// Operators perform operations on valueslet sum = 10 + 5; // + is an operatorlet isGreater = 10 > 5; // > is an operator
Operators work with values (operands)
sum → 15
isGreater → trueJavaScript 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
1000Note: The remainder operator (%) returns division remainder.
Assignment Operators
let x = 5;x += 3; // x = x + 3 → 8x -= 2; // x = x - 2 → 6x *= 4; // x = x * 4 → 24x /= 3; // x = x / 3 → 8x %= 5; // x = x % 5 → 3
Shorthand for common operationsThese 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"); // falseconsole.log(5 !== "5"); // trueconsole.log(10 > 5); // trueconsole.log(10 <= 10); // true
true
false
false
true
true
trueBest Practice: Always use strict equality (===) to avoid type coercion surprises.
Logical Operators
// AND (&&): Both must be trueconsole.log(true && true); // trueconsole.log(true && false); // false// OR (||): At least one trueconsole.log(false || true); // trueconsole.log(false || false); // false// NOT (!): Inverts booleanconsole.log(!true); // falseconsole.log(!false); // true
true
false
true
false
false
trueLogical 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 additionlet result = 2 + 3 * 4; // 14, not 20// Use parentheses to control orderlet withParens = (2 + 3) * 4; // 20// Logical AND before ORlet logicalResult = true || false && false; // true
Operations have execution order:
Parentheses > Multiplication > AdditionWhen in doubt, use parentheses to make your intentions clear.
Expressions vs Statements
// Expression: Produces a value3 * 5x > 10"Hello" + name// Statement: Performs an actionlet total = 3 * 5;if (x > 10) { ... }console.log("Hello");
Expressions evaluate to values
Statements perform actionsExpressions 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 surprisesconsole.log(1 + "1"); // "11" (not 2)console.log("5" - 3); // 2 (number)// Floating point precisionconsole.log(0.1 + 0.2); // 0.30000000000000004
Always use strict equality (===) and be cautious with type conversion in operations.
Practical Example: Shopping Cart
// Product pricesconst shirtPrice = 25.99;const pantsPrice = 39.99;const taxRate = 0.08;// User selectionslet shirtQty = 2;let pantsQty = 1;// Calculationslet subtotal = (shirtPrice * shirtQty) + (pantsPrice * pantsQty);let tax = subtotal * taxRate;let total = subtotal + tax;// Discount for orders over $50let hasDiscount = total > 50;if (hasDiscount) {total *= 0.9; // 10% discount}// Display resultslet 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 listenersdocument.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: trueYour Task: Interactive Operator Challenge
Make all three buttons functional by adding event listeners and implementing the required logic:
- Add an
addEventListenerto each button:calcBtn→calculate()compareBtn→compare()logicBtn→logicalTest()
- Implement functions:
calculate(): Compute(10 + 5) * 2and display result in the output divcompare(): Check if10 * 2is strictly equal to20and display boolean resultlogicalTest(): Evaluate(5 > 3) || (2 < 1)and display boolean result
- 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
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 valueslet sum = 10 + 5; // + is an operatorlet isGreater = 10 > 5; // > is an operator
Operators work with values (operands)
sum → 15
isGreater → trueJavaScript 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
1000Note: The remainder operator (%) returns division remainder.
Assignment Operators
let x = 5;x += 3; // x = x + 3 → 8x -= 2; // x = x - 2 → 6x *= 4; // x = x * 4 → 24x /= 3; // x = x / 3 → 8x %= 5; // x = x % 5 → 3
Shorthand for common operationsThese 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"); // falseconsole.log(5 !== "5"); // trueconsole.log(10 > 5); // trueconsole.log(10 <= 10); // true
true
false
false
true
true
trueBest Practice: Always use strict equality (===) to avoid type coercion surprises.
Logical Operators
// AND (&&): Both must be trueconsole.log(true && true); // trueconsole.log(true && false); // false// OR (||): At least one trueconsole.log(false || true); // trueconsole.log(false || false); // false// NOT (!): Inverts booleanconsole.log(!true); // falseconsole.log(!false); // true
true
false
true
false
false
trueLogical 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 additionlet result = 2 + 3 * 4; // 14, not 20// Use parentheses to control orderlet withParens = (2 + 3) * 4; // 20// Logical AND before ORlet logicalResult = true || false && false; // true
Operations have execution order:
Parentheses > Multiplication > AdditionWhen in doubt, use parentheses to make your intentions clear.
Expressions vs Statements
// Expression: Produces a value3 * 5x > 10"Hello" + name// Statement: Performs an actionlet total = 3 * 5;if (x > 10) { ... }console.log("Hello");
Expressions evaluate to values
Statements perform actionsExpressions 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 surprisesconsole.log(1 + "1"); // "11" (not 2)console.log("5" - 3); // 2 (number)// Floating point precisionconsole.log(0.1 + 0.2); // 0.30000000000000004
Always use strict equality (===) and be cautious with type conversion in operations.
Practical Example: Shopping Cart
// Product pricesconst shirtPrice = 25.99;const pantsPrice = 39.99;const taxRate = 0.08;// User selectionslet shirtQty = 2;let pantsQty = 1;// Calculationslet subtotal = (shirtPrice * shirtQty) + (pantsPrice * pantsQty);let tax = subtotal * taxRate;let total = subtotal + tax;// Discount for orders over $50let hasDiscount = total > 50;if (hasDiscount) {total *= 0.9; // 10% discount}// Display resultslet 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 listenersdocument.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: trueYour Task: Interactive Operator Challenge
Make all three buttons functional by adding event listeners and implementing the required logic:
- Add an
addEventListenerto each button:calcBtn→calculate()compareBtn→compare()logicBtn→logicalTest()
- Implement functions:
calculate(): Compute(10 + 5) * 2and display result in the output divcompare(): Check if10 * 2is strictly equal to20and display boolean resultlogicalTest(): Evaluate(5 > 3) || (2 < 1)and display boolean result
- 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