Skip to content

Beginner · First steps: values, variables and operators · topic 4 of 61 · 25 min

Operators and type coercion

Explanation

Operators combine values: + - * / % ** for maths, === and !== to compare, && || ! for logic, and ?? and ?. to deal with missing values. JavaScript sometimes converts types automatically (coercion), so always compare with === and convert text to numbers yourself.

Arithmetic operators

OperatorMeaningExampleResult
+add (or join strings)7 + 29
-subtract7 - 25
*multiply7 * 214
/divide (always a decimal result if needed)7 / 23.5
%remainder7 % 21
**power2 ** 101024

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 ++

javascript
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.

javascript
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)
Careful: Always use === and !==. The only common exception some teams allow is value == null, which is true for both null and undefined. If you need numbers from text, convert them yourself with Number(text).

+ 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.

javascript
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.

javascript
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.

javascript
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 crash

Precedence: 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.

Tip: Read a long expression from the inside out: brackets first, then **, then * / %, then + -, then comparisons, then && and finally ||.

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

Operators

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.

javascript
const cartTotal = 520;
const isPremium = false;
const coupon = undefined;
const freeDelivery = cartTotal >= 499 || isPremium;
const code = coupon ?? 'NONE';
console.log(freeDelivery, code);
Prints true NONE.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function isEven(n) that returns true when n is even and false when it is odd. Use the remainder operator.

Task 2 · Code · Javascript

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".

Task 3 · Code · Javascript

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

Question 1

1.What is '10' + 5 in JavaScript?

Question 2

2.What is '10' - 5?

Question 3

3.What is 0 ?? 100?

Question 4

4.let a = 3; const b = a++; What are a and b?

Question 5

5.What does 2 + 3 * 4 ** 2 give?

Read more (free)

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.

From Operators and expressions

Which expression is undefined behaviour?Related

Answer: i = i++ + 1

i is modified twice without sequencing.

From Operators

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.

From Operators and decisions: if, else and switch

hasTicket is true and hasId is false. What is hasTicket && hasId?Related

Answer: false

&& needs both to be true.

From Operators and conditions

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. 1 more topic in “First steps: values, variables and operators” before its exam: Numbers and Math.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.

← Previous: Variables: let, const and var