By the end of this lesson you can read and write the expressions that every program is made of: maths, comparisons, and combining true or false conditions.
Arithmetic
console.log(7 + 2); // 9
console.log(7 - 2); // 5
console.log(7 * 2); // 14
console.log(7 / 2); // 3.5
console.log(7 % 2); // 1
console.log(2 ** 3); // 8/ always gives a decimal result when needed, so 7 / 2 is 3.5. % is the remainder after division, handy for checking odd and even (n % 2 === 0) and for wrapping around a list. ** raises to a power. Dividing by zero gives Infinity, not an error.
The remainder keeps the sign of the left number: -5 % 3 is -2, and 10 % 2 is 0.
The + operator has a second job: if either side is text, it joins them. The next lesson shows why this causes surprises.
Assignment
= stores a value. The compound forms update a variable using its own value.
let x = 5;
x += 2; // 7 same as x = x + 2
x -= 1; // 6
x *= 3; // 18
x /= 2; // 9
x %= 5; // 4
x **= 2; // 16
console.log(x); // 16Increment and decrement
++ adds 1 and -- subtracts 1. Where you write them matters when you use the result.
let i = 5;
console.log(i++, i); // 5 6 returns the old value, then adds
console.log(++i, i); // 7 7 adds first, then returns the new value
console.log(i--, i); // 7 6As a standalone statement (i++;) the two forms do the same thing. Using them inside a bigger expression is a common source of confusion, so prefer a separate line.
Comparison
Comparisons produce true or false.
console.log(5 > 3); // true
console.log(5 >= 5); // true
console.log(5 < 3); // false
console.log(5 !== 5); // false
console.log(5 === "5"); // false different types
console.log(5 == "5"); // true converts first, avoidAlways prefer === and !==. They compare values without converting types. The loose == converts first and gives results that are hard to remember. The next lesson, on type conversion, explains the details.
Logical operators
&&(and):trueonly if both sides are truthy.||(or):trueif at least one side is truthy.!(not): flips true and false.
What is less obvious is that && and || do not always return true or false. They return one of their two operands.
console.log(true && "yes"); // yes
console.log(false && "yes"); // false
console.log(0 || "default"); // default
console.log("" || "x"); // x
console.log("hi" || "x"); // hi
console.log(!true); // false
console.log(!!"text"); // true double ! converts to a boolean
console.log(!!0); // falseThe rule: || returns the first operand that is truthy (or the last if none is), and && returns the first falsy operand (or the last if none is). That is why value || "default" is a common way to provide a fallback. The values counted as "falsy" are covered in the Control flow section.
Nullish coalescing
|| has one problem: it replaces every falsy value, including a valid 0 or an empty string. The ?? operator replaces only null and undefined.
console.log(null ?? "d"); // d
console.log(0 ?? "d"); // 0
console.log(0 || "d"); // dIf 0 is a legitimate value, such as a quantity, use ??.
Precedence
Operators have an order of priority. Multiplication and division happen before addition and subtraction, and ** before both.
console.log((2 + 3) * 4); // 20
console.log(2 + 3 * 4); // 14
console.log(2 ** 3 ** 2); // 512 (** works right to left: 3 ** 2 first)
console.log((-2) ** 2); // 4If you write -2 ** 2 without brackets, JavaScript refuses with a SyntaxError, because the intention is ambiguous. When an expression is not obvious at a glance, add brackets. They cost nothing and help the next reader.
Try it
Edit the numbers and predict each result before running.
<pre id="out"></pre>
<script>
const a = 17;
const b = 5;
const rows = [
"a + b = " + (a + b),
"a / b = " + (a / b),
"a % b = " + (a % b),
"a ** 2 = " + (a ** 2),
"a > b = " + (a > b),
"a % 2 === 0 ? " + (a % 2 === 0),
"a > 10 && b > 10 : " + (a > 10 && b > 10),
"a > 10 || b > 10 : " + (a > 10 || b > 10),
"b ?? 99 : " + (b ?? 99)
];
document.getElementById("out").textContent = rows.join("\n");
</script>Reading an expression
When you meet a long expression, read it in the order the engine does. First find the brackets and work from the inside out. Then apply **, then multiplication, division and remainder, then addition and subtraction, then the comparisons, then &&, then ||. Writing the intermediate steps as separate named variables is often clearer than a single long line, and it gives you something to print with console.log when the result is not what you expected. If you are unsure of a result, test the expression in the console. A few seconds of experiment is better than a guess that turns into a bug later.
Common mistakes
- Using
=instead of===in a comparison.=assigns. Comparing needs===. - Expecting
/to give a whole number.7 / 2is3.5. UseMath.floorwhen you need the whole part. - Chaining comparisons like in maths.
1 < x < 10does not mean what you think. Writex > 1 && x < 10. - Relying on precedence you have not checked. Add brackets.
- Using
||for defaults when0is valid. Use??instead. - Packing
++into complex expressions. Keep it on its own line.
Exercise
- With
const total = 47;print how many full groups of 5 fit (Math.floor), and the left-over amount (%). - Write a boolean expression that is true when a number
nis even and greater than 10. Try several values. - Make
let count = 0;and use+=and*=to reach 12 in at least three steps, printing after each. - Print
undefined ?? "none"and"" ?? "none"and explain why the results differ from||.
Next: Type conversion and equality.
Key points
- Arithmetic operators are + - * / % and **, and + also joins strings.
- Assignment operators such as += and *= update a variable in one step.
- Comparison operators return true or false, and === compares without converting types.
- and || return one of their operands rather than a plain true or false, and ?? only replaces null or undefined.
- Multiplication happens before addition, and brackets let you control the order.