Step: Basics | Player: 02_Variables and_Types
Learning Objectives
- The Arithmetic/Assignment/Comparison/Logic operator can be used depending on the situation.
- Understand the difference between
==and===and use===as the default. - Short-circuit evaluation and nullish merging (
??) can be used. - Optional chaining (
?.) allows you to safely access properties. - Can explain the difference between expressions and statements.
1. Arithmetic and assignment
In addition to the four basic operations, there are the remaining %, power **, and increase/decrease ++/--. Assignment operators +=, -=, etc. are short and frequently used.
let n = 10;
n **= 2; // 100
n %= 7; // 100 % 7 = 2
2. Comparison operators
== converts and compares types, and === compares whether even the types are the same. Use === in almost any situation.
0 == ""; // true
0 === ""; // false
NaN === NaN; //false → Use Number.isNaN
3. Logical operators and shorthand evaluation
&&, || does not evaluate only to boolean and returns the original operand. ?? uses the right-hand value only when null or undefined.
const name = userName || "anonymous"; //If userName is falsy then "anonymous"
const port = process.env.PORT ?? 3000; //3000 only when null/undefined
4. Optional chaining
?. stops evaluating if the left side is null or undefined and returns undefined. This is useful for safely accessing deep objects.
const city = user?.address?.city ?? "unknown";
fn?.(); //Called if fn exists
arr?.[0]; //If arr is present, it is the first element
Core example
| file | Contents covered |
|---|---|
01_arithmetic.js |
Arithmetic/Assignment operator and powers, remainder |
02_comparison.js |
Comparison of == vs === with NaN |
03_logical.js |
Shortened evaluation of &&, ` |
04_optional_chaining.js |
Safe property access with ?. |
⚠️ Common Mistakes
- When you want to use
0as a valid value in the0 || defaultpattern,??is required, but||is used. - Assuming that the floating point calculation result (
0.1 + 0.2 !== 0.3) is accurate. - Attempting to compare with
=== NaN, forgetting thatNaN === NaNis false. - Subtle bug due to differences between
++xandx++. - When only the first step is made optional and the last step is omitted, like
a?.b.c.
❓ Frequently Asked Questions (FAQ)
Q1. Should == never be used? A. x == null is not recommended except for idioms that check null/undefined at once.
Q2. Which is the default, ?? or ||? A. If the intention is “default value when there is no value”, ?? is safer. This is because 0 and "" can be treated as valid values.
Q3. What is the difference between an expression and a statement? A. An expression evaluates to a value. Statements perform actions. if (...) is a statement, and a ? b : c is an expression.