Manuals / JavaScript / Ch 2

A · FundamentalsBeginner50 min read

2. Values, variables & control flow

JavaScript · 56 pages source format

JavaScript has eight types (seven primitives + object). let and const replace var. Control flow — if/else, loops, switch — is how programs make decisions. Master ===, truthy/falsy, and template literals before moving on.

What you'll learn

  • Primitives vs objects
  • let/const and block scope
  • if/else, for, while
  • === vs ==
  • Template literals

Types and typeof

Primitives: string, number, boolean, null, undefined, symbol, bigint. Everything else is an object (including arrays and functions). typeof null returns "object" — a famous bug never fixed for compatibility.

typeof "hello"   // "string"
typeof 42        // "number"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object" (historical quirk)
typeof {}        // "object"
typeof []        // "object"
typeof (() => {}) // "function"

Do this now

In the console, test typeof on 10 different values. Write a comment explaining null and undefined.

Clear?

let, const, and naming

Use const by default. Use let when reassignment is required. Never use var in new code — function scope causes bugs. Names: camelCase for variables, UPPER_SNAKE for constants.

Do this now

Create variables for a user profile: name, age, isActive. Use const where possible. Reassign isActive with let.

Pro tip. If you never reassign, use const. Linters enforce this.

Clear?

Comparison and truthiness

Always use === and !==. == coerces types and surprises beginners. Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy.

  • === strict equality — no coercion
  • == loose equality — avoid
  • Falsy: false, 0, "", null, undefined, NaN
  • Truthy: everything else including [] and {}

Do this now

Predict then run: 0 == false, 0 === false, "" == false, null == undefined. Document results.

Clear?

Control flow

if/else for branching. for...of for arrays (prefer over classic for). while for unknown iteration counts. switch for many discrete cases.

function grade(score) {
  if (score >= 90) return "A"
  if (score >= 80) return "B"
  if (score >= 70) return "C"
  if (score >= 60) return "D"
  return "F"
}

for (const s of [95, 72, 58]) {
  console.log(`${s} → ${grade(s)}`)
}

Do this now

Write a function grade(score) returning A/B/C/D/F using if/else. Loop an array of scores and print each grade.

Clear?

Template literals

Backticks allow ${expression} interpolation and multiline strings. Prefer over + concatenation.

Do this now

Build a multiline HTML snippet for a user card using template literals and your profile variables.

Clear?

Checklist