JavaScript course menu
JavaScript Operators: Arithmetic, Assignment, Increment, Logical and More
Learn JavaScript operators: arithmetic, assignment and compound assignment (+=, -=), increment and decrement (prefix vs postfix), comparison, logical AND, OR and NOT, nullish coalescing (??), optional chaining (?.), the ternary operator and precedence.
On this page
Operators combine values into new values. You have already used arithmetic operators in Numbers and Math; this lesson covers the rest.
Assignment#
= assigns a value. Compound assignment operators update a variable using its current value:
let balance = 1000;
balance += 500; // balance = balance + 500
balance -= 200;
balance *= 2;
balance /= 4;
console.log(balance);
let message = "Hello";
message += ", world";
console.log(message);650
Hello, worldIncrement and decrement#
++ adds 1 and -- subtracts 1:
let count = 5;
count++;
console.log(count);
count--;
count--;
console.log(count);6
4When used inside another expression, position matters: count++ (postfix) gives the old value, then adds; ++count (prefix) adds first and gives the new value:
let a = 5;
console.log(a++);
console.log(a);
let b = 5;
console.log(++b);5
6
6To avoid confusion, most code uses ++ only as a statement on its own, or writes count += 1.
Comparison#
They all produce true or false. The next lesson, Comparisons, Truthy and Falsy, covers them in depth.
Logical operators#
const age = 20;
const hasTicket = true;
console.log(age >= 18 && hasTicket);
console.log(age < 12 || age > 60);
console.log(!hasTicket);true
false
falseShort-circuiting#
&& and || stop as soon as the result is known, and they return one of their operands, not necessarily true or false:
console.log("Asha" || "Guest");
console.log("" || "Guest");
console.log(0 && "never evaluated");
console.log("logged in" && "show dashboard");Asha
Guest
0
show dashboarda || breturnsaif it is truthy, otherwiseb. It was the classic way to provide a default.a && breturnsaif it is falsy, otherwiseb.
Nullish coalescing: ??#
|| treats all falsy values (0, "", false) as missing, which is often wrong. ?? only falls back when the value is null or undefined:
const savedVolume = 0;
console.log(savedVolume || 50);
console.log(savedVolume ?? 50);
let nickname;
console.log(nickname ?? "No nickname");50
0
No nicknameUse ?? for default values. ??= assigns only if the variable is currently null or undefined: options.limit ??= 10;.
Optional chaining: ?.#
Reading a property of undefined or null throws an error. ?. stops and returns undefined instead:
const user = { name: "Ravi", address: null };
console.log(user.address?.city);
console.log(user.profile?.photo ?? "default.png");
console.log(user.getAge?.());undefined
default.png
undefinedThis is very useful with data from APIs, where some fields may be missing.
The ternary operator#
condition ? valueIfTrue : valueIfFalse chooses between two values in one expression:
const stock = 0;
const label = stock > 0 ? "In stock" : "Sold out";
console.log(label);Sold outtypeof and other operators#
typeof xgives the type name (Data Types).inchecks whether an object has a property:"name" in user.instanceofchecks whether an object was created by a class:date instanceof Date.delete obj.propremoves a property.
Precedence#
When an expression has several operators, precedence decides the order. Roughly from first to last: grouping (), member access and calls, ! and typeof, **, * / %, + -, comparisons, ===, &&, || and ??, ? :, and assignment.
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(true || false && false);14
20
true&& binds tighter than ||. When in doubt, add parentheses; they cost nothing and make intent clear. (JavaScript does not let you mix ?? with && or || without parentheses, for exactly this reason.)
Practice#
Practice exercise
A cart has const items = 3, const pricePerItem = 120 and an optional const coupon = undefined. Compute the total, apply a discount of coupon?.discount percent, using 0 if there is no coupon, and print Free delivery if the final total is at least 300, otherwise Delivery: ₹40.
Show solution
const items = 3;
const pricePerItem = 120;
const coupon = undefined;
const subtotal = items * pricePerItem;
const discount = coupon?.discount ?? 0;
const total = subtotal - (subtotal * discount) / 100;
console.log(total);
console.log(total >= 300 ? "Free delivery" : "Delivery: ₹40");360
Free deliveryKey takeaway#
Finished this lesson?