Chapters

FundamentalsChapter 11 of 21

Operators

The symbols that combine values, and the order they apply in.

The families

Operators do the work between values. There are five groups worth naming now, each with its own chapter after this one.

FamilyExamplesProduces
Arithmetic+ - * / % **a number
Assignment= += -= *=stores a value
Comparison=== !== < > <= >=a boolean
Logical&& || !a value or a boolean
Othertypeof ?? ?. ternarydepends
JavaScript

JavaScript

const a = 7;
const b = 2;

console.log(a + b, a % b, a ** b);
console.log(a > b, a === 7);
console.log(a > b && b > 0);

Output

9 1 49
true true
true

Operands

Most operators take two values, one on each side. A few take one: ! flips a boolean, and - in front of a number negates it.

JavaScript

JavaScript

const ready = false;

console.log(!ready);
console.log(-(3 + 4));

Output

true
-7

Precedence

When several operators appear together, some bind tighter than others. Multiplication before addition, comparison before &&, and assignment last of all.

JavaScript

JavaScript

console.log(2 + 3 * 4);
console.log((2 + 3) * 4);

Output

14
20

Tip

Nobody remembers the full precedence table, and nobody should have to read code that depends on it. Add brackets when the grouping is not obvious at a glance.

The ternary

One operator takes three operands: a condition, a value if true, and a value if false. It is an expression, so it can go where a value is expected.

JavaScript

JavaScript

const hour = 20;
const greeting = hour < 12 ? 'Morning' : 'Evening';

console.log(greeting);

Output

Evening

Keep it to one decision. Nested ternaries are famously hard to read, and an if statement is right there.

Test yourself

2 questions

What does 2 + 3 * 4 produce?

Show the answer

14 Multiplication binds tighter than addition, so the multiplication happens first.

What is the ternary operator for?

Show the answer

Choosing between two values as an expression Because it is an expression it can sit inside a template literal or an argument, where an if statement cannot.

Next chapter

Arithmetic

Doing sums, including the two operators people forget.