Operators: arithmetic, comparison and logical
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
What operators do
An operator takes one or more values and produces a new value. You already used + and =. In this lesson we go through the groups you need.
Arithmetic operators
const a = 17;
const b = 5;
console.log(a + b); // 22
console.log(a - b); // 12
console.log(a * b); // 85
console.log(a / b); // 3.4
console.log(a % b); // 2 remainder
console.log(a ** 2); // 289 power
let count = 0;
count++; // add one
count++;
count--; // subtract one
console.log(count); // 1
The % operator gives the remainder after division. It is useful more often than you would think. n % 2 === 0 checks if a number is even. It is also how you make something wrap around, such as moving to the next item in a list and returning to the first.
The + operator does two jobs. With numbers it adds. With a string on either side it joins text:
console.log(1 + 2); // 3
console.log("1" + 2); // "12"
console.log("5" - 2); // 3 (minus only works with numbers, so "5" is converted)
That last pair is the source of many bugs. When types are mixed, + prefers text but - prefers numbers. Convert values explicitly and you avoid the problem.
Assignment shortcuts
| Short form | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
Comparison operators
Comparison operators give back a boolean.
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 <= 4); // false
console.log(5 === 5); // true
console.log(5 !== 6); // true
Use === and not ==
JavaScript has two equality operators. The double == converts types before comparing, and gives strange results. The triple === compares type and value with no conversion.
console.log(0 == ""); // true (surprising)
console.log("1" == 1); // true
console.log(null == undefined); // true
console.log(0 === ""); // false
console.log("1" === 1); // false
My rule is to always use === and !==. The only place I accept == null is when I want to check for both null and undefined in one go, and even then I prefer to write it out so the reader does not wonder.
Logical operators
There are three: && (and), || (or) and ! (not).
const age = 25;
const hasTicket = true;
console.log(age >= 18 && hasTicket); // true, both must be true
console.log(age < 18 || hasTicket); // true, at least one is true
console.log(!hasTicket); // false, flips the value
They return values, not just booleans
This is a feature that often surprises beginners. || returns the first truthy value it finds. && returns the first falsy value, or the last value if all are truthy.
const userName = "";
const display = userName || "Guest";
console.log(display); // "Guest"
const user = { name: "Sara" };
console.log(user && user.name); // "Sara"
The first pattern is a common way to give a default value. It has a catch. || treats 0 and "" as empty, so 0 || 10 gives 10 even if zero was a real answer.
Nullish coalescing
The ?? operator fixes that. It only falls back when the left side is null or undefined:
const score = 0;
console.log(score || 100); // 100 (probably not what you wanted)
console.log(score ?? 100); // 0 (correct)
I reach for ?? for defaults now, and keep || for real true/false logic.
Optional chaining
If you read a property from something that might be undefined, JavaScript throws an error. The ?. operator stops and returns undefined instead:
const settings = {};
console.log(settings.theme?.colour); // undefined, no crash
// console.log(settings.theme.colour); // TypeError
The ternary operator
For a quick choice between two values, use the ? : form:
const age = 16;
const label = age >= 18 ? "adult" : "minor";
console.log(label); // "minor"
Read it as "if the condition, then this, otherwise that". Keep it for simple cases. A ternary inside a ternary is hard to read, and an if statement is clearer there.
Operator order
Multiplication and division run before addition and subtraction, just like in school maths. ** runs before *. When in doubt, add brackets: (a + b) * c. Brackets cost nothing and make your intent obvious.
Common mistakes
- Using = when you meant ===.
if (x = 5)assigns 5 and is always true. Always type three equals signs when comparing. - Adding numbers read from a form. They are strings, so
+joins them. - Using || for defaults when 0 or an empty string is valid. Use
??. - Comparing objects.
{} === {}isfalse, because two separate objects are never equal. We will look at why in the objects lesson.
Try it yourself
- Write code that tells you whether a number is even or odd using
%and a ternary. - Predict
"10" + 5,"10" - 5,"10" * "2". Then run them. - Set
const volume = 0;and show whatvolume || 50andvolume ?? 50return. - Given
const user = {}, safely readuser.address?.citywithout causing an error.
const a = 17;
const b = 5;
console.log(a + b); // 22
console.log(a - b); // 12
console.log(a * b); // 85
console.log(a / b); // 3.4
console.log(a % b); // 2 remainder
console.log(a ** 2); // 289 power
let count = 0;
count++; // add one
count++;
count--; // subtract one
console.log(count); // 1
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account