JavaScript + Node.js track

Lesson 03 · Part 1: Basics

Operators & Expressions

Arithmetic, comparison, logical operators, optional chaining and nullish coalescing

Part 1: Basics2 min readFree lesson

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

  1. When you want to use 0 as a valid value in the 0 || default pattern, ?? is required, but || is used.
  2. Assuming that the floating point calculation result (0.1 + 0.2 !== 0.3) is accurate.
  3. Attempting to compare with === NaN, forgetting that NaN === NaN is false.
  4. Subtle bug due to differences between ++x and x++.
  5. 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.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_arithmetic.jsJavaScript
/** Look at arithmetic/assignment operators.*/
const a = 17;
const b = 5;

console.log("a + b =", a + b);
console.log("a - b =", a - b);
console.log("a * b =", a * b);
console.log("a / b =", a / b);
console.log("a % b =", a % b);
console.log("a ** b =", a ** b);

let n = 10;
n += 5;  console.log("n += 5 →", n);
n *= 2;  console.log("n *= 2 →", n);
n **= 2; console.log("n **= 2 →", n);
src/02_comparison.jsJavaScript
/** Check the difference between == and === and NaN comparison.*/
console.log(0 == "");        // true
console.log(0 === "");       // false
console.log(null == undefined);  // true
console.log(null === undefined); // false

console.log(NaN === NaN);             // false
console.log(Number.isNaN(NaN));       // true
console.log(Object.is(NaN, NaN));     // true
src/03_logical.jsJavaScript
/** &&, ||, ?? Compare the shortened evaluation of .*/
const empty = "";
const zero = 0;

console.log(empty || "default");   //"default" (empty is falsy)
console.log(empty ?? "default");   //"" (not null/undefined)
console.log(zero || 100);          // 100
console.log(zero ?? 100);          // 0

//&& returns the first false or last value
console.log(true && "ok");         // "ok"
console.log(0 && "skip");          // 0
src/04_optional_chaining.jsJavaScript
/** Access safely with optional chaining.*/
const user = {
  name: "Ada",
  address: { city: "London" },
};

console.log(user?.address?.city);          // "London"
console.log(user?.company?.name);          // undefined
console.log(user?.company?.name ?? "unemployed"); //“unemployed”

const maybeFn = undefined;
console.log(maybeFn?.());                  //undefined (not an error)

const arr = null;
console.log(arr?.[0]);                     // undefined

Assignment

homework_01.js

  • Define the two numbers a and b as constants, and output the results +, -, *, /, %, ** as console.table.

homework_02.js

  • Safely import nested object order.customer.address.city using optional chaining.
  • If not, use “Address not entered” as the default.
  • Try testing with objects that are missing some properties.
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/** Prints the arithmetic results of two numbers in a table.*/
const a = 13;
const b = 4;

const result = {
  "+": a + b,
  "-": a - b,
  "*": a * b,
  "/": a / b,
  "%": a % b,
  "**": a ** b,
};

console.table(result);
homework_02.jsJavaScript
/** Obtain safe values through optional chaining and nullish merging.*/
const orders = [
  { id: 1, customer: { name: "A", address: { city: "Seoul" } } },
  { id: 2, customer: { name: "B" } },
  { id: 3 },
];

for (const order of orders) {
  const city = order?.customer?.address?.city ?? "Address not entered";
  console.log(`Order ${order.id}: ${city}`);
}

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now