Same ideas, JavaScript's spelling
Every language you are likely to have met has decisions, loops and functions, and JavaScript's look familiar: the curly-brace syntax came from Java, which took it from C. If you know Python, the main differences are braces instead of indentation and parentheses around conditions.
Two things make this lesson more than a syntax tour. First, JavaScript has several loops and several ways to write a function, and they are not interchangeable: some were added later to fix problems with the earlier ones, and you need to know which to reach for. Second, functions in JavaScript are ordinary values. You can store one in a variable, pass it to another function, and return it as a result. That one idea, borrowed from Scheme in 1995, is the foundation of most JavaScript you will ever read, from array methods to event handlers to promises.
Decisions
An if statement runs a block when its condition is truthy (recall the eight falsy values from the last lesson). Chain alternatives with else if. For a choice between two values, the conditional operator condition ? a : b is shorter. A switch compares one value against several cases using strict equality (===).
// Decisions: if/else, the conditional operator and switch.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function describeDay(day) {
switch (day) {
case "Saturday":
case "Sunday":
return "weekend";
case "Friday":
return "almost the weekend";
default:
return "a working day";
}
}
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 75) {
return "B";
} else if (score >= 50) {
return "C";
} else {
return "not yet";
}
}
for (const year of [1900, 2000, 2024, 2026]) {
console.log(year, isLeapYear(year) ? "is a leap year" : "is not a leap year");
}
for (const day of ["Monday", "Friday", "Sunday"]) {
console.log(`${day}: ${describeDay(day)}`);
}
console.log([95, 75, 74, 12].map(grade));1900 is not a leap year
2000 is a leap year
2024 is a leap year
2026 is not a leap year
Monday: a working day
Friday: almost the weekend
Sunday: weekend
[ 'A', 'B', 'C', 'not yet' ]Notes on what you see:
&&(and),||(or) and!(not) short-circuit:a && bdoes not evaluatebwhenais falsy. The leap-year rule reads directly as the Gregorian calendar states it: divisible by 4 and not by 100, or divisible by 400.- In
describeDay,"Saturday"has no code of its own, so it falls through to the"Sunday"case. Here that is deliberate. Without areturnorbreak, every case falls through into the next one, which is a classic bug; exercise one shows it. Linters flag fall-through that is not obviously intended. gradereturns as soon as a condition matches, so each test can assume the earlier ones failed. Some teams prefer early returns like this to deep nesting:if (score >= 90) return "A";on one line, then the next.[95, 75, 74, 12].map(grade)passes the functiongradeitself tomap, which calls it on each element and collects the results. You will see much more of this below.
Always use braces around blocks, even one-line ones, unless the whole statement fits on the same line as the if. A brace-less if followed by two indented lines runs only the first one conditionally, however it is indented.
Loops
JavaScript has five loops. In modern code you will mostly see two of them, plus the array methods of lesson six.
// Loops: for, for...of, while, do...while, break and continue.
// Classic counting loop.
let row = "";
for (let i = 1; i <= 5; i++) {
row += i * i + " ";
}
console.log(row.trim());
// for...of visits values: of an array, of a string's characters.
const rivers = ["Nile", "Amazon", "Mekong"];
for (const river of rivers) {
if (river.length > 5) continue; // skip long names
console.log("short name:", river);
}
for (const ch of "añil") {
console.log(ch, ch.codePointAt(0));
}
// while: repeat until a condition fails. Collatz: halve evens, 3n + 1 for odds.
let n = 27;
let steps = 0;
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
console.log("27 reaches 1 after", steps, "steps");
// break: stop at the first match.
const readings = [12, 15, 31, 18, 40];
let firstHot = -1;
for (let i = 0; i < readings.length; i++) {
if (readings[i] > 30) {
firstHot = i;
break;
}
}
console.log("first reading above 30 is at index", firstHot);
// do...while runs its body at least once.
let attempts = 0;
do {
attempts++;
} while (attempts < 0);
console.log("attempts:", attempts);1 4 9 16 25
short name: Nile
a 97
ñ 241
i 105
l 108
27 reaches 1 after 111 steps
first reading above 30 is at index 2
attempts: 1How to choose:
| Loop | Use it when | Example in the program |
|---|---|---|
for (const x of iterable) | you want each value of an array, string, Map, Set or other iterable | the rivers and the letters of "añil" |
for (let i = 0; i < n; i++) | you need the index, a step other than 1, or to walk two positions at once | the squares, the first hot reading |
while (condition) | you don't know in advance how many times to repeat | the Collatz steps |
do { ... } while (condition) | the body must run at least once, such as asking again until an answer is valid | the attempts counter |
for (const key in object) | you want an object's property names (lesson five has better tools) | not used |
break leaves the loop; continue skips to the next pass. Both apply to the innermost loop. To leave an outer loop from inside an inner one, give the outer loop a label and name it: outer: for (const row of grid) { for (const cell of row) { if (cell === target) break outer; } }. Labels are rare in everyday code, and many teams prefer to move the nested loops into a function and return from it, which reads more plainly. A loop written while (true) { ... } with a break inside is also perfectly respectable when the exit test naturally sits in the middle of the body. for...of iterates a string by code point, so ñ arrives as one character even if it is stored as two UTF-16 units. The Collatz sequence, by the way, is one of mathematics' famous open problems: nobody has proved that every starting number reaches 1, though every number ever tried does.
Misconception
"for...in is the way to loop over an array." for...in visits property names, as strings, and it also visits inherited enumerable properties. On an array it gives "0", "1", "2", which are strings, so i + 1 concatenates. Use for...of for values, or for (const [i, value] of list.entries()) when you need both.
Three ways to write a function
Definition— function declaration, expression and arrow function
A function declaration is a statement, function name(params) { ... }, that creates a function and binds it to name throughout the enclosing scope. A function expression is the same syntax used as a value, typically stored with const name = function (params) { ... }. An arrow function, (params) => expression or (params) => { statements }, is a shorter expression form that also differs in how it treats this (next lesson).
// Three ways to write a function.
// 1. A declaration is hoisted: it can be called before the line that defines it.
console.log(area(3, 4));
function area(width, height) {
return width * height;
}
// 2. A function expression stored in a constant.
const perimeter = function (width, height) {
return 2 * (width + height);
};
// 3. An arrow function. With a single expression, the braces and return can go.
const diagonal = (width, height) => Math.hypot(width, height);
const square = (x) => x * x;
const makePoint = (x, y) => ({ x, y }); // parentheses around an object literal
console.log(perimeter(3, 4), diagonal(3, 4), square(9), makePoint(1, 2));
// Parameters: defaults, missing arguments, rest parameters.
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet("Wanjiru"), greet("Mateo", "Hola"));
function describe(first, second) {
return `first=${first}, second=${second}`;
}
console.log(describe(1)); // a missing argument is undefined
console.log(describe(1, 2, 3)); // an extra argument is ignored
function average(...numbers) {
if (numbers.length === 0) return NaN;
let sum = 0;
for (const x of numbers) sum += x;
return sum / numbers.length;
}
console.log(average(2, 4, 9), average());
// A function without a return statement returns undefined.
function logOnly(message) {
console.log("log:", message);
}
console.log(logOnly("hi"));12
14 5 81 { x: 1, y: 2 }
Hello, Wanjiru! Hola, Mateo!
first=1, second=undefined
first=1, second=2
5 NaN
log: hi
undefinedThe details that matter in practice:
- Hoisting. A declaration is created before any code in its scope runs, which is why
area(3, 4)works on the line above it. A function stored in aconstexists only from its line onward; calling it earlier throws aReferenceError. Teams differ on style: many use declarations for named, top-level functions (they read well and hoist), and arrows for short functions passed as arguments. - Arrow syntax. One parameter may drop its parentheses (
x => x * x), though formatters usually add them back. With braces you need an explicitreturn. To return an object literal from a one-expression arrow, wrap it in parentheses:(x, y) => ({ x, y }). Without them, the braces are read as a block, and the function returnsundefined. ({ x, y }is shorthand for{ x: x, y: y }.) - Arguments are flexible. JavaScript never checks the number of arguments. Missing ones are
undefined; extra ones are ignored. That is why defaults are so useful:greeting = "Hello"applies whenever the argument isundefined. A default can refer to earlier parameters, as infunction f(a, b = a * 2). - Rest parameters (
...numbers) gather the remaining arguments into a real array. Old code uses theargumentsobject for this; prefer rest parameters. - Every call returns something. Without a
return, or with a barereturn;, the result isundefined. - Many optional settings? Pass one object. A function with five positional parameters is hard to call correctly. The common idiom is a single options object with named fields and defaults,
function connect({ host = "localhost", port = 8080 } = {}) { ... }, called asconnect({ port: 9000 }). The braces in the parameter list are destructuring, covered in lesson six.
Functions are values
Because a function is a value, you can do with it everything you do with a number or a string. A function that takes or returns another function is called a higher-order function, and JavaScript code is full of them.
// Functions are values: store them, pass them, return them.
const twice = (f, x) => f(f(x));
const addThree = (n) => n + 3;
console.log(twice(addThree, 10));
// A function that builds functions.
function makeRounder(decimals) {
const factor = 10 ** decimals;
return (x) => Math.round(x * factor) / factor;
}
const toCents = makeRounder(2);
const toWhole = makeRounder(0);
console.log(toCents(3.14159), toWhole(3.14159));
// Passing behaviour to a library function: sort compares with our function.
const cities = [
{ name: "Lima", population: 10.1 },
{ name: "Cairo", population: 22.6 },
{ name: "Oslo", population: 1.1 },
];
const byPopulation = (a, b) => b.population - a.population;
console.log(cities.toSorted(byPopulation).map((c) => c.name));
// Building a pipeline from small functions.
const pipe = (...fns) => (input) => {
let value = input;
for (const fn of fns) value = fn(value);
return value;
};
const slugify = pipe(
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.normalize("NFD").replaceAll(/\p{M}/gu, ""), // drop accents: ó becomes o
(s) => s.replaceAll(/[^a-z0-9]+/g, "-"),
);
console.log(slugify(" Hello World from Kraków "));16
3.14 3
[ 'Cairo', 'Lima', 'Oslo' ]
hello-world-from-krakowWalk through each part:
twice(addThree, 10)computesaddThree(addThree(10)), which is 16. The function is passed without parentheses:addThreeis the function,addThree(10)is a call.makeRounder(2)returns a new function that still knowsfactorwas 100, even thoughmakeRounderhas finished. That memory is a closure, the subject of the next lesson.toSorted(ECMAScript 2023) returns a sorted copy; it calls your comparator with pairs of elements and expects a negative number ifashould come first, a positive one ifbshould, and 0 for a tie.b.population - a.populationsorts from largest to smallest.pipetakes any number of functions and returns one function that applies them in order. The slug step uses two regular expressions, patterns between slashes:/\p{M}/gumatches combining accent marks after the text has been decomposed bynormalize("NFD"), and/[^a-z0-9]+/gmatches each run of characters that are not letters or digits. MDN's regular expressions guide in the references covers them.
These are the same ideas as Lumenary Math's functions: a rule that turns inputs into outputs, which you can compose. JavaScript lets you build and combine such rules at run time.
Functions that call themselves
A function may call itself. Recursion is the natural tool whenever data contains smaller copies of itself: folders inside folders, comments with replies to replies, a menu with submenus, the parsed structure of a JSON document. The trick is to answer the question for one level and hand each smaller piece to the same function.
// Recursion: a function that solves a problem by calling itself on smaller pieces.
const projects = {
name: "projects",
files: ["notes.txt"],
folders: [
{ name: "site", files: ["index.html", "app.js"], folders: [] },
{
name: "data",
files: [],
folders: [{ name: "2026", files: ["jan.csv", "feb.csv", "mar.csv"], folders: [] }],
},
],
};
function countFiles(folder) {
let total = folder.files.length;
for (const sub of folder.folders) {
total += countFiles(sub); // the same question, on a smaller folder
}
return total;
}
function listPaths(folder, prefix = "") {
const here = `${prefix}${folder.name}/`;
const paths = folder.files.map((file) => here + file);
for (const sub of folder.folders) {
paths.push(...listPaths(sub, here));
}
return paths;
}
console.log(countFiles(projects));
console.log(listPaths(projects));
// Every call uses stack space, and the stack is limited.
const depth = (n) => (n === 0 ? 0 : 1 + depth(n - 1));
console.log(depth(1000));
try {
depth(1_000_000);
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}6
[
'projects/notes.txt',
'projects/site/index.html',
'projects/site/app.js',
'projects/data/2026/jan.csv',
'projects/data/2026/feb.csv',
'projects/data/2026/mar.csv'
]
1000
RangeError: Maximum call stack size exceededEvery recursive function needs a base case that stops it: here, a folder with no subfolders simply returns its own count, because the loop body never runs. (paths.push(...list) appends every element of list; the ... spread syntax is lesson six.)
The last lines show the price. Each call that has not yet returned occupies a frame on the call stack, and engines cap the stack at roughly ten thousand frames or so (the exact limit depends on the engine and the size of each frame). Recursion as deep as a folder tree is perfectly safe; recursion as deep as a million-element list is not. The 2015 standard specified "proper tail calls", which would let a call in final position reuse its frame, but only Safari's engine implemented them; V8 and SpiderMonkey never did. So in JavaScript, when the depth depends on the size of the input, professionals rewrite the recursion as a loop, often with an explicit array used as a stack.
Example— Why callbacks are everywhere
When a browser runs your code because someone clicked a button, it needs to know what to run. You tell it by handing over a function: button.addEventListener("click", handleClick). The same pattern runs through the whole platform: a timer takes a function to call later, array.map takes a function to apply to each element, and a promise takes functions to call when a result arrives. A function passed to be called later is a callback.
Common misconceptions
Misconception
"An arrow function is just a shorter function." It is shorter, but it also has no this, arguments or prototype of its own, cannot be called with new, and is never hoisted. Lesson four shows why the missing this is usually exactly what you want inside a method, and occasionally exactly wrong.
Misconception
"switch compares like ==." It uses strict equality, ===. switch ("1") will not match case 1:.
Misconception
"JavaScript will tell me if I call a function with the wrong number of arguments." It never does. Missing arguments are undefined and extras are ignored silently. Default parameters, careful naming, an options object, and, in larger projects, TypeScript are how professionals protect themselves.
Misconception
"return on its own line, followed by the value on the next, returns the value." Automatic semicolon insertion puts a semicolon right after a bare return at the end of a line, so the function returns undefined. Start the returned expression on the same line as return, or open a parenthesis there.
Exercises
Predict, then check by running each program with node.
1. Control flow and functions
CoreComputationalWhat does this program print?
function size(n) {
let label = "";
switch (n) {
case 1:
label += "one ";
case 2:
label += "two ";
break;
case 3:
label += "three ";
default:
label += "many";
}
return label.trim();
}
console.log(size(1), "|", size(3));
2. Control flow and functions
Warm-upComputationalWhat number does this print?
let n = 6;
let steps = 0;
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
console.log(steps);
3. Control flow and functions
CoreComputationalWhat does this print?
const out = [];
for (const i in ["a", "b", "c"]) {
out.push(i + 1);
}
console.log(out.join(" "));
4. Control flow and functions
CoreComputationalWhat does this print?
const wrap = (v) => { value: v };
console.log(wrap(42));
5. Control flow and functions
CoreComputationalWhat does this print?
function f(a, b = a * 2, ...rest) {
return a + b + rest.length;
}
console.log(f(3), f(3, 1, 7, 7));
6. Control flow and functions
CoreComputationalWhat does this program print?
try {
console.log(cube(2));
} catch (err) {
console.log(err.name);
}
const cube = (x) => x ** 3;
console.log(cube(2));
7. Control flow and functions
StretchComputationalWhat number does this print?
const makeAdder = (n) => (x) => x + n;
const add5 = makeAdder(5);
console.log(add5(add5(1)));
Further reading and resources
- MDN: Control flow and error handling · Mozilla and contributors
- MDN: Loops and iteration · Mozilla and contributors
- MDN: Functions · Mozilla and contributorsDeclarations, expressions, arrows, parameters and scope.
- MDN: Arrow function expressions · Mozilla and contributorsIncluding the differences from ordinary functions, which lesson four explains.