Beginner · First steps: values, variables and operators · topic 4 of 61 · 25 min
Operators and type coercion
Explanation
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | add (or join strings) | 7 + 2 | 9 |
| - | subtract | 7 - 2 | 5 |
| * | multiply | 7 * 2 | 14 |
| / | divide (always a decimal result if needed) | 7 / 2 | 3.5 |
| % | remainder | 7 % 2 | 1 |
| ** | power | 2 ** 10 | 1024 |
Unlike some languages, 7 / 2 is 3.5, not 3. To get a whole number, use Math.floor(7 / 2) or Math.trunc. The remainder operator % is useful to test even numbers (n % 2 === 0) and to wrap around (index % length).
Assignment shortcuts and ++
let stock = 10;
stock += 5; // 15
stock -= 3; // 12
stock *= 2; // 24
stock++; // 25
console.log(stock); // 25
let a = 5;
console.log(a++); // 5 (gives the old value, then adds 1)
console.log(++a); // 7 (adds 1 first, then gives the value)Comparing: === versus ==
=== (strict equality) is true only when both the type and the value match. == (loose equality) first converts the values to the same type and then compares. That conversion is called type coercion, and its rules are hard to remember.
console.log(5 === 5); // true
console.log('5' === 5); // false (string vs number)
console.log('5' == 5); // true ('5' is converted to 5)
console.log(0 == ''); // true (surprise!)
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(NaN === NaN); // false (NaN is never equal to anything)+ with strings
If either side of + is a string, + joins (concatenates) instead of adding. The other operators (- * /) always try to convert to numbers. This is why form values cause bugs.
console.log('10' + 5); // '105'
console.log('10' - 5); // 5
console.log('3' * '4'); // 12
console.log(1 + 2 + '3'); // '33' (1 + 2 = 3 first, then '3' + '3')Logical operators and short-circuit
&& (and) is true when both sides are true. || (or) is true when at least one side is true. ! (not) flips true and false. They short-circuit: && stops at the first falsy value and || stops at the first truthy value, and they return that VALUE, not just true or false.
console.log(true && false); // false
console.log(0 || 'default'); // 'default'
console.log('Asha' && 'ok'); // 'ok'
console.log(!true); // false?? and ?. for missing values
The nullish coalescing operator ?? gives the right side only when the left side is null or undefined. Unlike ||, it keeps 0 and empty strings. Optional chaining ?. reads a property only if the thing before it exists; otherwise it gives undefined instead of crashing.
const settings = { volume: 0 };
console.log(settings.volume || 50); // 50 (wrong! 0 was a real value)
console.log(settings.volume ?? 50); // 0 (right)
const order = { customer: null };
console.log(order.customer?.address?.city); // undefined, no crashPrecedence: who goes first
As in school maths, * and / happen before + and -. ** happens before *. Comparison comes after maths, then &&, then ||. When in doubt, add brackets: (a + b) * c is clearer than relying on memory.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Operators and type coercion · 1/6
In this lesson you will use operators to calculate, compare and make decisions.
Prefer a video by a teacher? Find free videos on “javascript operators type coercion == vs === nullish coalescing” on YouTube ↗
In real life: Free delivery on a grocery app
A grocery app gives free delivery when the cart is at least ₹499 OR the user has a premium plan. The discount code field may be missing, so the code uses ?? for a default and === for exact matches.
const cartTotal = 520;
const isPremium = false;
const coupon = undefined;
const freeDelivery = cartTotal >= 499 || isPremium;
const code = coupon ?? 'NONE';
console.log(freeDelivery, code);Practice (0/3 done)
Write a function isEven(n) that returns true when n is even and false when it is odd. Use the remainder operator.
Form fields arrive as text. Write a function addPrices(a, b) that takes two strings like "120" and "80" and returns their sum as a NUMBER (200), not "12080".
Write a function volumeOrDefault(settings) that returns settings.volume, or 50 when volume is missing (null or undefined). A volume of 0 is a real choice and must be kept. settings itself may be undefined.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Numbers and MathFirst steps: values, variables and operators · same module
- Operators and expressionsJava Programming (Core to Spring Boot) · Getting started with Java
- OperatorsC Programming (from zero to systems) · Operators and control flow
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Operators and conditionsFrontend Web Development · JavaScript basics
- WHERE: comparison and logicSQL and Databases · SELECT: filtering and sorting
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is '10' + 5 in JavaScript?
Answer: '105'
With a string on one side, + joins text.
What is '10' - 5?
Answer: 5
- always converts to numbers, so 10 - 5 = 5.
What is 0 ?? 100?
Answer: 0
?? only replaces null and undefined, so 0 is kept.
let a = 3; const b = a++; What are a and b?
Answer: a 4, b 3
Postfix ++ gives the old value (3) to b, then increases a to 4.
What does 2 + 3 * 4 ** 2 give?
Answer: 50
** first: 4 ** 2 = 16; then 3 * 16 = 48; then 2 + 48 = 50.
Integer.MAX_VALUE + 1 gives…Related
Answer: Integer.MIN_VALUE (-2147483648)
int overflow wraps around silently.
Which expression is undefined behaviour?Related
Which type can NOT be used in a switch?Related
Answer: std::string
switch needs an integral or enum value. Use if / else if for strings.
hasTicket is true and hasId is false. What is hasTicket && hasId?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “First steps: values, variables and operators” before its exam: Numbers and Math.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.