4. Operators and Expressions in JavaScript
What Are Operators?
Operators are special symbols that tell JavaScript to perform an action — like adding numbers, comparing values, or joining strings.
An *expression* is any piece of code that produces a value. For example, `2 + 2` or `name + ' is learning JS'` are both expressions.
Arithmetic Operators
- `+` — Addition
- `-` — Subtraction
- `*` — Multiplication
- `/` — Division
- `%` — Modulus (remainder after division)
- `**` — Exponentiation (power)
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a ** b); // 1000String Concatenation
You can use the `+` operator to join (concatenate) strings together.
let firstName = "Ada";
let lastName = "Lovelace";
console.log(firstName + " " + lastName); // Ada LovelaceAssignment Operators
Assignment operators store values in variables, sometimes while performing an operation at the same time.
- `=` — Assign a value
- `+=` — Add and assign
- `-=` — Subtract and assign
- `*=` — Multiply and assign
- `/=` — Divide and assign
let x = 10;
x += 5; // same as x = x + 5
console.log(x); // 15Comparison Operators
Comparison operators are used to compare two values and return a Boolean (`true` or `false`).
- `==` — Equal to (compares value only)
- `===` — Strict equal to (compares value and type)
- `!=` — Not equal to (value only)
- `!==` — Strict not equal to (value and type)
- `>` — Greater than
- `<` — Less than
- `>=` — Greater than or equal to
- `<=` — Less than or equal to
console.log(5 == '5'); // true (same value)
console.log(5 === '5'); // false (different type)
console.log(8 > 3); // true
console.log(4 <= 2); // falseLogical Operators
Logical operators are used to combine or invert conditions. They’re often used in `if` statements.
- `&&` — AND (both must be true)
- `||` — OR (at least one must be true)
- `!` — NOT (reverses the result)
let age = 20;
let hasID = true;
console.log(age >= 18 && hasID); // true
console.log(age < 18 || hasID); // true
console.log(!hasID); // falseType Coercion Gotchas
JavaScript can automatically convert types in some cases — this is called *type coercion*. It can cause unexpected results if you’re not careful.
console.log('5' + 5); // '55' (string concatenation)
console.log('5' - 2); // 3 (string converted to number)
console.log(true + 1); // 2 (true becomes 1)Mini Challenge
Write a small script that checks if someone is old enough to vote. If their age is 18 or more, log 'You can vote!'. Otherwise, log 'You’re too young.'
// Example:
let age = 17;
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You're too young.");
}Key Takeaway
Operators form the logic engine of your code. They let you combine, compare, and evaluate data — powering everything from math to decisions.