Tutorials / JavaScript Fundamentals / Operators: arithmetic, comparison and logical

Operators: arithmetic, comparison and logical

6 min read and ??.
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. 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 formSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = 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. {} === {} is false, because two separate objects are never equal. We will look at why in the objects lesson.

Try it yourself

  1. Write code that tells you whether a number is even or odd using % and a ternary.
  2. Predict "10" + 5, "10" - 5, "10" * "2". Then run them.
  3. Set const volume = 0; and show what volume || 50 and volume ?? 50 return.
  4. Given const user = {}, safely read user.address?.city without causing an error.
and ??.
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