A Quick Tour of JavaScript, Part 2: Functions, Control Flow and Classes
The second half of the JavaScript tour: function declarations and arrow functions, functions as values, methods and this, if/else, loops with for...of, switch, a first class with a getter and a subclass, error handling, and a first look at async/await and modules.
kvi5hnuCode Sprout team member6 min readOn this page
Part 1 of the tour covered values: variables, objects, arrays and operators. This part covers the code that does things: functions, decisions, loops and classes, finishing with a glimpse of asynchronous code. Again, everything here is explained properly later. The aim is a working picture, and every example runs.
The theme this time is a fitness tracker that records workouts.
Functions
A function is a named, reusable block of code with parameters (inputs) and a return value (output):
function caloriesBurned(minutes, perMinute) {
return minutes * perMinute;
}
console.log(caloriesBurned(30, 8)); // 240
console.log(caloriesBurned(45, 11)); // 495
function greet(name = "athlete") { // a default value for a missing argument
return `Ready, ${name}?`;
}
console.log(greet("Meera"));
console.log(greet());
console.log(caloriesBurned(30)); // missing argument: undefined * 8 is NaN
240
495
Ready, Meera?
Ready, athlete?
NaN
JavaScript doesn't complain when you pass too few or too many arguments. Missing ones become undefined, which is why the last call produced NaN (not a number) instead of an error. Default values like name = "athlete" handle the common case.
Functions are values
In JavaScript a function is a value like a number or a string: you can store it in a variable, put it in an object, or pass it to another function. The compact arrow function syntax is common for small functions:
const double = n => n * 2; // one parameter: no parentheses needed
const pace = (km, minutes) => minutes / km; // two parameters
const describe = km => { // a body with several statements
const label = km >= 10 ? "long" : "short";
return `${km} km is a ${label} run`;
};
console.log(double(21));
console.log(pace(5, 27.5));
console.log(describe(12));
// Pass functions to other functions:
const distances = [3, 12, 5, 21];
console.log(distances.map(double)); // apply to each element
console.log(distances.filter(km => km > 4)); // keep matching elements
console.log(distances.map(describe));
42
5.5
12 km is a long run
[ 6, 24, 10, 42 ]
[ 12, 5, 21 ]
[
'3 km is a short run',
'12 km is a long run',
'5 km is a short run',
'21 km is a long run'
]
Passing small functions to map, filter and similar methods is everyday JavaScript. You'll see it in almost every codebase.
Methods and this
A function stored in an object's property is a method. Inside a method, this refers to the object the method was called on:
const runner = {
name: "Kabir",
totalKm: 0,
log(km) { // method shorthand syntax
this.totalKm += km; // this is runner, because we call runner.log(...)
return this; // returning this allows chaining
},
report() {
return `${this.name} ran ${this.totalKm} km`;
},
};
runner.log(5).log(8).log(3);
console.log(runner.report());
Kabir ran 16 km
this is one of the trickiest parts of JavaScript because its value depends on how a function is called, not where it's written. Arrow functions don't have their own this at all. Part 8 untangles all of it.
Making decisions
if/else chooses between branches, and the conditional operator ?: chooses between two values:
function zone(heartRate) {
if (heartRate < 100) {
return "warm-up";
} else if (heartRate < 140) {
return "fat burn";
} else if (heartRate < 170) {
return "cardio";
} else {
return "peak";
}
}
for (const bpm of [92, 128, 165, 181]) {
const label = bpm >= 170 ? "slow down!" : "ok";
console.log(bpm, zone(bpm), label);
}
92 warm-up ok
128 fat burn ok
165 cardio ok
181 peak slow down!
switch compares one value against several cases with ===:
function equipment(sport) {
switch (sport) {
case "run":
return "shoes";
case "swim":
return "goggles";
case "bike":
case "spin": // two cases sharing one result
return "helmet";
default:
return "nothing special";
}
}
console.log(["run", "spin", "yoga"].map(equipment));
[ 'shoes', 'helmet', 'nothing special' ]
Loops
The for...of loop visits each element of an array (or any other iterable, such as a string). It's the loop you'll write most often. The classic counting for loop and while exist too:
const week = [5, 0, 8, 3, 0, 12, 6]; // km run each day
let total = 0;
for (const km of week) { // each element in turn
total += km;
}
console.log("total:", total);
for (let day = 0; day < week.length; day++) { // when you need the index
if (week[day] === 0) continue; // skip rest days
if (week[day] > 10) {
console.log(`day ${day}: long run, ${week[day]} km`);
}
}
let target = 1, weeks = 0;
while (target < 21) { // repeat while the condition holds
target *= 1.5;
weeks++;
}
console.log(`reach a half marathon distance in ${weeks} weeks`);
for (const [day, km] of week.entries()) { // index and value together
if (km === 0) console.log(`rest on day ${day}`);
}
total: 34
day 5: long run, 12 km
reach a half marathon distance in 8 weeks
rest on day 1
rest on day 4
break leaves a loop early and continue skips to the next iteration. The [day, km] syntax in the last loop is destructuring: it unpacks the two-element pairs that entries() produces into two variables.
Classes
A class is a template for creating objects that share methods. The constructor runs when you create an object with new:
class Workout {
constructor(sport, minutes) {
this.sport = sport;
this.minutes = minutes;
}
get hours() { // a getter: read it like a property
return this.minutes / 60;
}
toString() {
return `${this.sport} for ${this.minutes} min`;
}
}
class Run extends Workout { // a subclass inherits everything above
constructor(minutes, km) {
super("run", minutes); // call the parent constructor first
this.km = km;
}
pace() {
return (this.minutes / this.km).toFixed(2) + " min/km";
}
toString() { // override and extend the parent version
return `${super.toString()} (${this.km} km)`;
}
}
const swim = new Workout("swim", 45);
const run = new Run(50, 10);
console.log(String(swim));
console.log(String(run), "pace", run.pace());
console.log(run.hours.toFixed(2)); // inherited getter, no parentheses
console.log(run instanceof Run, run instanceof Workout);
swim for 45 min
run for 50 min (10 km) pace 5.00 min/km
0.83
true true

Under the hood, JavaScript classes are built on prototypes: objects inherit from other objects. Class syntax is the modern, readable way to use that mechanism. Part 9 shows what happens beneath it.
When things go wrong: exceptions
throw signals an error, and try/catch handles it:
function parseDuration(text) {
const match = /^(\d+):(\d\d)$/.exec(text); // a regular expression for m:ss
if (!match) {
throw new Error(`bad duration "${text}"`);
}
return Number(match[1]) * 60 + Number(match[2]);
}
for (const input of ["4:35", "12:05", "4m35s"]) {
try {
console.log(input, "=", parseDuration(input), "seconds");
} catch (err) {
console.log("skipped:", err.message);
}
}
4:35 = 275 seconds
12:05 = 725 seconds
skipped: bad duration "4m35s"
A glimpse of asynchronous code
Many operations, such as network requests, timers and reading files, finish later. JavaScript doesn't stop and wait for them. Instead, they return a promise of a future result, and an async function can await it:
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function syncWorkouts() {
console.log("uploading...");
await wait(100); // pause this function, not the whole program
console.log("uploaded");
return 3;
}
syncWorkouts().then(count => console.log(`${count} workouts synced`));
console.log("this line runs before the upload finishes");
uploading...
this line runs before the upload finishes
uploaded
3 workouts synced
The order of those lines is the key idea of asynchronous JavaScript: while syncWorkouts waits, the rest of the program keeps running. Part 13 explains the event loop that makes this work.
Modules
Real programs are split into files called modules. A module exports what it wants to share, and other modules import it:
export function average(numbers) {
return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
}
import { average } from "./stats.js";
console.log(average([5, 8, 3])); // 5.333333333333333
Part 10 covers modules, including how they work in browsers and in Node.js.
Common questions
Function declaration or arrow function: which should I use?
Both are everywhere. A common style: function declarations for named, top-level functions, and arrow functions for short callbacks like items.map(x => x.id). The real differences are that arrow functions don't have their own this or arguments and can't be used with new. Part 8 covers this in detail.
Why does for...in give me "0", "1", "2" instead of the elements?
for...in loops over property names (keys), and for an array those are the indexes as strings. Use for...of for the values of an array, and for...in (or better, Object.keys) for the keys of a plain object.
Do I have to use classes to write object-oriented code?
No. Plain objects, functions that create objects ("factory functions") and closures are all common alternatives, and JavaScript code often favors them. Classes are useful when you create many similar objects with shared behavior, or when a framework expects them.
Is await blocking like a sleep in other languages?
No. await pauses only the async function it's in. The rest of the program, including event handlers and other async functions, keeps running. That's why the line after the call printed first in the example.
Summary
- Functions take parameters and return values. Missing arguments are
undefined, and default parameters fill gaps. - Functions are values: store them, pass them to
map/filter, and write small ones as arrow functions. - In a method,
thisis the object the method was called on. if/else,?:,switch,for...of,forandwhilework much like in C-family languages.- Classes bundle a constructor, methods and getters.
extendsandsupercreate subclasses. throw/try/catchhandle errors.async/awaithandles results that arrive later, and modules split code into files.
Practice Questions
What does this code produce?
[1, 2, 3, 4].filter(n => n % 2 === 0).map(n => n * 10)
Answer
[20, 40]. filter keeps the even numbers [2, 4], and map multiplies each by 10.
In the runner example, what would runner.log(5).log(8) do if log didn't return this?
Answer
runner.log(5) would return undefined, so .log(8) would try to call a method on undefined and throw a TypeError. Returning this is what makes method chaining possible.
Why must a subclass constructor call super(...) before using this?
Answer
In a subclass, the parent constructor is what creates and initializes the object. Until super(...) runs, there is no this to use, and touching it throws a ReferenceError.
In the async example, why did "this line runs before the upload finishes" print second, not last?
Answer
syncWorkouts() ran synchronously until its first await, printing "uploading...", and then returned a promise. The program continued with the next statement and printed the line. The rest of syncWorkouts ran 100 ms later, when the timer finished.
What is run.hours, and where does hours come from?
const run = new Run(30, 6);
Answer
0.5. hours is a getter defined on Workout; Run inherits it, and it computes 30 / 60.
Previous: A Quick Tour of JavaScript, Part 1: Values, Variables, Objects, Arrays and Operators
Next: Your First Real JavaScript Program: A Word Frequency Report from Standard Input

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.