Complete JavaScript Course Module 2: Beginner: Variables and Data Types

JavaScript Operators: Assignment, Comparison and Operator Precedence

  • Beginner
  • Lesson 2.5
  • 7 min read
  • 8 of 76 in the course

In short

JavaScript operators are the symbols that work with values: assignment, comparison, math and joining text. Learn every operator group, pre vs post increment and operator precedence. What are the operator groups in JavaScript?

JavaScript operators are the symbols that work with values: assignment, comparison, math and joining text. Learn every operator group, pre vs post increment and operator precedence.

What are the operator groups in JavaScript?

An operator is a symbol (or a short word) that takes one or more values and gives back a result. The values it works on are called operands. In 4 + 2, the + is the operator and 4 and 2 are the operands. You met the math operators briefly in the Numbers and Math lesson. Here is the full family in one place, so you can see how they fit together:

GroupOperatorsExampleResult
Arithmetic+ - * / % **7 % 31
Assignment= += -= *= /= %= **=x += 2adds 2 to x
Increment / decrement++ --x++adds 1 to x
Comparison=== !== == != > < >= <=5 > 3true
Logical&& || !true && falsefalse
Nullish??null ?? "guest""guest"
String+ +="Hi " + "Sam""Hi Sam"
Conditional (ternary)? :age >= 18 ? "adult" : "child"one of two values
Typetypeoftypeof 42"number"

Logical operators and the ternary operator have their own lesson. This lesson goes deeper into assignment, increment, comparison, joining strings and the order in which JavaScript works things out.

Assignment operators: =, +=, -=, *= and more

The assignment operator = puts a value into a variable. It does not mean "equals" like in math class. Read score = 10 as "score becomes 10".

The compound assignment operators do a calculation and an assignment in one step. x += 5 is a short way to write x = x + 5.

OperatorSame asExample (x starts at 10)x becomes
=x = 44
+=x = x + yx += 515
-=x = x - yx -= 37
*=x = x * yx *= 220
/=x = x / yx /= 42.5
%=x = x % yx %= 31
**=x = x ** yx **= 2100
??=x = x ?? yx ??= 010 (only set if x is null or undefined)

Here is a shopping basket that uses them:

let total = 0;            // start with an empty basket

total += 12.5;            // add a book
total += 7.5;             // add a pen set
console.log(total);       // Output: 20

total -= 5;               // apply a $5 voucher
total *= 1.2;             // add 20% tax
console.log(total);       // Output: 18

let nickname;             // undefined for now
nickname ??= "Guest";     // only fills it in because it was empty
console.log(nickname);    // Output: Guest

Each line changes total based on its current value. Compound operators only work on variables made with let, because a const cannot be given a new value.

Increment and decrement: what is the difference between x++ and ++x?

++ adds 1 and -- subtracts 1. You can put them after the variable (postfix, x++) or before it (prefix, ++x). On a line of its own, both do the same thing. The difference appears when you use the result in the same expression:

  • Postfix x++: gives you the old value, then adds 1.
  • Prefix ++x: adds 1 first, then gives you the new value.
let tickets = 5;

const a = tickets++;     // a gets the old value, then tickets goes up
console.log(a, tickets); // Output: 5 6

const b = ++tickets;     // tickets goes up first, then b gets the new value
console.log(b, tickets); // Output: 7 7

let lives = 3;
console.log(lives--);    // Output: 3   (shows old value)
console.log(lives);      // Output: 2

Think of a ticket machine. With tickets++ you are handed the current ticket and then the counter moves on. With ++tickets the counter moves on first, and you get the new number.

Tip: To avoid confusion, use ++ and -- on their own line, like count++;. Then it never matters which form you pick.

Comparison operators and joining strings with +

Comparison operators compare two values and always give back a boolean, true or false.

OperatorMeaningExampleResult
===Strictly equal (same value and type)5 === "5"false
!==Strictly not equal5 !== 3true
==Loosely equal (converts types first)5 == "5"true
> / <Greater / less than10 > 9true
>= / <=Greater / less than or equal18 >= 18true

Always prefer === and !==; the Type Conversion lesson explains why == can surprise you. Strings are compared letter by letter, by their character codes, so "apple" < "banana" is true, but "Zebra" < "apple" is also true, because capital letters come first.

The + operator has a second job: when one side is a string, it joins (concatenates) the values into one string instead of adding them. JavaScript reads from left to right, which can give surprising results:

const name = "Lina";
const items = 3;

console.log("Hello, " + name + "!");      // Output: Hello, Lina!
console.log("Items: " + 2 + 1);           // Output: Items: 21
console.log(2 + 1 + " items");            // Output: 3 items
console.log("Items: " + (2 + 1));         // Output: Items: 3

let message = "Order";
message += " #" + 1042;
console.log(message);                     // Output: Order #1042

console.log(`${name} has ${items} items`); // Output: Lina has 3 items

In "Items: " + 2 + 1, the first + makes the string "Items: 2", and then + 1 joins another character. In 2 + 1 + " items", the numbers are added first because both are numbers. Brackets fix the first case. For most text, template literals (the backtick strings) are easier to read than many + signs.

Common mistake: Writing = when you mean === inside an if. if (role = "admin") assigns "admin" to role and is always true. Use if (role === "admin").

Operator precedence table: which operator runs first?

Operator precedence is the set of rules that decides which part of an expression is worked out first, like "multiply before add" in school math. Operators higher in this table run first:

OrderOperatorsNotes
1( )Brackets (grouping) always win
2. [] ()Property access and function calls
3x++ x--Postfix increment
4++x --x ! -x typeofPrefix and unary operators
5**Power (works right to left)
6* / %
7+ -Also string joining
8< <= > >=
9=== !== == !=
10&&
11|| ??
12? :Ternary
13= += -= and other assignmentsRun last, right to left
const price = 40;
const quantity = 2;
const discount = 10;

console.log(price * quantity - discount);   // Output: 70
console.log(price * (quantity - discount)); // Output: -320

const inStock = 5;
console.log(inStock > 0 && quantity <= inStock); // Output: true

console.log(2 ** 3 ** 2);   // Output: 512   (3 ** 2 first, then 2 ** 9)
console.log((2 ** 3) ** 2); // Output: 64

const isMember = false;
const total = price * quantity - (isMember ? discount : 0);
console.log(total);         // Output: 80

In the first line, * runs before -. In the comparison line, > and <= run before &&, so you get two booleans joined by "and". The last example needs brackets around the ternary, because - has higher precedence than ? :.

You do not need to learn the whole table by heart. When in doubt, add brackets: they cost nothing and make your intention clear to the next person who reads your code. JavaScript even forces you to use them in some places: mixing ?? with || or && without brackets is a syntax error. The full list is on MDN's operator precedence page.

Practice exercise

Build a tiny game score tracker. Start with let score = 0; and let level = 1;. Use += to add 50 points three times, *= to double the score as a bonus, and ++ to go up one level. Then log Level 2 - Score: 300 using a template literal. Finally, predict and then check what console.log("Score: " + score + 100) prints, and fix it with brackets.

Hint: the unfixed line joins "100" onto the end of the text. Wrap score + 100 in brackets to add first.

Key takeaways

  • = assigns a value; compound operators like += and *= update a variable based on its current value.
  • x++ gives the old value then adds 1; ++x adds 1 first and gives the new value.
  • Comparison operators always return true or false; use === and !==.
  • When either side is a string, + joins text instead of adding.
  • Precedence decides what runs first, and brackets let you choose the order yourself.