From Zero to Senior · The LabالعربيةGitHub

Chapter 10

Functions

6 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • package a piece of code as a named, reusable function
  • pass information in with parameters and get results out with return
  • understand where variables live: scope
  • write short arrow functions and use them with map, filter and reduce
  • rebuild the ticket kiosk from small, clear functions

Examples

10.1 Your first function

Think of a function as a little machine. You put something in (like an age), it does its work, and something comes out (like a price). You build the machine once and use it as often as you like, without thinking about its insides again.

greet.js⤓ File
function greet(name) {
  return `Hello, ${name}!`;
}

const message = greet("Sara");
console.log(message);
console.log(greet("Omar"));
Recorded output$ node greet.js
Hello, Sara!
Hello, Omar!

10.2 Functions make code reusable

Here are the kiosk’s pricing rules as a function. Once written, it can be used anywhere, as often as you like:

price.js⤓ File
function ticketPrice(age) {
  if (age < 4) {
    return 0;
  }
  if (age < 13 || age >= 65) {
    return 6;
  }
  return 10;
}

console.log(ticketPrice(2));
console.log(ticketPrice(9));
console.log(ticketPrice(34));
console.log(ticketPrice(70));
Recorded output$ node price.js
0
6
10
6

10.3 Several parameters and default values

A function can take several parameters, separated by commas. The order matters: the first argument goes to the first parameter. A parameter can also have a default value, used when the caller leaves it out:

params.js⤓ File
function area(width, height) {
  return width * height;
}

function welcome(name, language = "en") {
  if (language === "ar") {
    return `مرحباً يا ${name}`;
  }
  return `Welcome, ${name}`;
}

console.log(area(4, 5));
console.log(welcome("Lina"));
console.log(welcome("Lina", "ar"));
Recorded output$ node params.js
20
Welcome, Lina
مرحباً يا Lina

10.4 Scope: where variables live

A variable created inside a function exists only inside that function. This is called scope:

scope.js⤓ File
const tax = 0.14;

function withTax(price) {
  const total = price + price * tax;
  return total;
}

console.log(withTax(100));
console.log(typeof total);
Recorded output$ node scope.js
114
undefined

10.5 Arrow functions and array methods

When the body is a single expression, the arrow function returns it automatically, without return or curly brackets. Arrow functions shine when you give a function to another function. Arrays have three famous methods that do exactly that:

arrow.js⤓ File
const double = (n) => n * 2;
console.log(double(21));

const prices = [12, 5, 30, 8];

const withVat = prices.map((p) => p * 1.1);
console.log(withVat);

const cheap = prices.filter((p) => p < 10);
console.log(cheap);

const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);
Recorded output$ node arrow.js
42
[ 13.200000000000001, 5.5, 33, 8.8 ]
[ 5, 8 ]
55

10.6 Project: a kiosk made of functions

Let us rebuild the kiosk the way a professional would: from small functions, each with one job. One function knows the base price, one applies the members’ day, and one builds a receipt line from a visitor:

kiosk.js⤓ File
// Small functions, each with one job
function ticketPrice(age) {
  if (age < 4) return 0;
  if (age < 13 || age >= 65) return 6;
  return 10;
}

function applyMemberDay(price, isMember, day) {
  if (isMember && day === "Tuesday") {
    return price / 2;
  }
  return price;
}

function receiptLine(visitor) {
  const base = ticketPrice(visitor.age);
  const price = applyMemberDay(base, visitor.member, "Tuesday");
  return `${visitor.name}: ${price}`;
}

// Each visitor is an object; you will learn objects in Chapter 11.
const visitors = [
  { name: "Sara", age: 34, member: true },
  { name: "Adam", age: 9, member: false },
  { name: "Huda", age: 70, member: true },
];

for (const visitor of visitors) {
  console.log(receiptLine(visitor));
}
Recorded output$ node kiosk.js
Sara: 5
Adam: 6
Huda: 3

Practice projects

Project 10.1 · Easy

A unit converter

Write a set of small conversion functions, plus one helper for rounding, and use them together.

You will practise: parameters, return, default values, and calling functions inside other calls.

Steps
  1. Write kmToMiles(km) (× 0.621371), kgToPounds(kg) (× 2.20462) and celsiusToFahrenheit(c).
  2. Write a helper round(value, digits = 1) that returns Number(value.toFixed(digits)). The default means you usually do not have to pass digits.
  3. Print four conversions, passing the result of one function straight into another: round(kmToMiles(10)).
  4. Convert the length of a marathon, 42.195 km, with two decimal places.
  5. Add one more converter of your own, for example litres to cups.

Hint: toFixed returns a string; Number(…) turns it back into a number, so you can keep calculating with it.

Solution
converter.js⤓ File
function kmToMiles(km) {
  return km * 0.621371;
}

function kgToPounds(kg) {
  return kg * 2.20462;
}

function celsiusToFahrenheit(c) {
  return (c * 9) / 5 + 32;
}

function round(value, digits = 1) {
  return Number(value.toFixed(digits));
}

console.log("10 km =", round(kmToMiles(10)), "miles");
console.log("70 kg =", round(kgToPounds(70)), "pounds");
console.log("37 °C =", round(celsiusToFahrenheit(37)), "°F");
console.log("42.195 km =", round(kmToMiles(42.195), 2), "miles");
Recorded output$ node converter.js
10 km = 6.2 miles
70 kg = 154.3 pounds
37 °C = 98.6 °F
42.195 km = 26.22 miles

Project 10.2 · Medium

Password strength checker

Rate passwords as weak, okay or strong, using small helper functions that each check one thing.

You will practise: functions that return booleans, early returns, looping over the letters of a string, and combining small functions.

Steps
  1. Write hasDigit(text): loop over the characters with for…of, and return true as soon as one is a digit. After the loop, return false.
  2. Write hasUpper(text): a text has a capital letter if it changes when you make it lower case.
  3. Write strength(password): give one point each for 8 or more characters, 12 or more characters, a digit, and a capital letter.
  4. Turn the points into a word with early returns: 0–1 weak, 2–3 okay, 4 strong.
  5. Test four passwords, from the weakest to the strongest.

Hint: length matters more than anything else for a password’s strength. A long, unusual sentence beats a short word with symbols.

Solution
password.js⤓ File
function hasDigit(text) {
  for (const char of text) {
    if ("0123456789".includes(char)) return true;
  }
  return false;
}

function hasUpper(text) {
  return text !== text.toLowerCase();
}

function strength(password) {
  let points = 0;
  if (password.length >= 8) points++;
  if (password.length >= 12) points++;
  if (hasDigit(password)) points++;
  if (hasUpper(password)) points++;

  if (points <= 1) return "weak";
  if (points <= 3) return "okay";
  return "strong";
}

for (const password of ["cat", "sunshine", "sunshine2026", "Sunshine2026Blue"]) {
  console.log(password, "→", strength(password));
}
Recorded output$ node password.js
cat → weak
sunshine → weak
sunshine2026 → okay
Sunshine2026Blue → strong

Project 10.3 · Challenge

Sales report with map, filter and reduce

A small shop has a list of orders. Answer three business questions, each in one or two lines, without writing a single for loop.

You will practise: arrow functions, map, filter, reduce, and chaining them.

Steps
  1. Create an array of five orders, each an object with a product, a quantity and a price.
  2. Write an arrow function lineTotal(order) that returns quantity × price.
  3. Total revenue: map each order to its line total, then reduce to one sum.
  4. Big orders: filter the orders whose line total is 25 or more, and print how many.
  5. Stickers sold: filter the sticker orders, then reduce their quantities. Writing .filter(…) and .reduce(…) on separate lines makes the chain easy to read.

Hint: read a chain from top to bottom as a sentence: “orders, only the stickers, add up the quantities”. Professional code is full of chains like this.

Solution
sales.js⤓ File
const orders = [
  { product: "book", quantity: 2, price: 25 },
  { product: "sticker", quantity: 5, price: 3 },
  { product: "mug", quantity: 1, price: 8 },
  { product: "book", quantity: 1, price: 25 },
  { product: "sticker", quantity: 10, price: 3 },
];

const lineTotal = (order) => order.quantity * order.price;

const revenue = orders.map(lineTotal).reduce((sum, value) => sum + value, 0);
const bigOrders = orders.filter((order) => lineTotal(order) >= 25);
const stickersSold = orders
  .filter((order) => order.product === "sticker")
  .reduce((sum, order) => sum + order.quantity, 0);

console.log("Revenue:", revenue);
console.log("Orders of 25 or more:", bigOrders.length);
console.log("Stickers sold:", stickersSold);
Recorded output$ node sales.js
Revenue: 128
Orders of 25 or more: 3
Stickers sold: 15

Exercises

Exercise 10.1 · Easy

Write isEven(n) that returns true or false. Test it with 4, 7 and 0.
The book's short answer
function isEven(n) { return n % 2 === 0; } gives true, false, true.
Show the solution
is-even.js⤓ File
function isEven(n) {
  return n % 2 === 0;
}

console.log(isEven(4));
console.log(isEven(7));
console.log(isEven(0));
Recorded output$ node is-even.js
true
false
true

Exercise 10.2 · Easy

Write celsiusToFahrenheit(c), using c * 9 / 5 + 32. What is 37 °C in Fahrenheit?
The book's short answer
function celsiusToFahrenheit(c) { return c * 9 / 5 + 32; }; 37 °C is 98.6 °F.
Show the solution
celsius.js⤓ File
function celsiusToFahrenheit(c) {
  return c * 9 / 5 + 32;
}

console.log(celsiusToFahrenheit(37)); // body temperature
console.log(celsiusToFahrenheit(0)); // water freezes
console.log(celsiusToFahrenheit(100)); // water boils
Recorded output$ node celsius.js
98.6
32
212

Exercise 10.3 · Medium

Write maxOf(numbers) that returns the largest number in an array, using the algorithm from Chapter 2. Then find the built-in way with Math.max on MDN.
The book's short answer
The largest-card algorithm inside a function. The built-in way is Math.max(...numbers).
Show the solution
max-of.js⤓ File
// The largest-card algorithm from Chapter 2, inside a function.
function maxOf(numbers) {
  let largest = numbers[0];
  for (const n of numbers) {
    if (n > largest) {
      largest = n;
    }
  }
  return largest;
}

const cards = [7, 3, 12, 5, 9];
console.log(maxOf(cards));

// The built-in way: ... spreads the array into separate arguments, Math.max(7, 3, 12, 5, 9).
console.log(Math.max(...cards));

// Both agree on negative numbers too:
console.log(maxOf([-4, -9, -1]), Math.max(-4, -9, -1));
Recorded output$ node max-of.js
12
12
-1 -1

Exercise 10.4 · Medium

Given an array of prices, use filter and map to get the prices over 10 with a 20% discount applied, rounded with toFixed(2).
The book's short answer
prices.filter((p) => p > 10).map((p) => (p * 0.8).toFixed(2))
Show the solution
discounts.js⤓ File
const prices = [8, 12.5, 30, 9.99, 15];

// Keep the prices over 10, then take 20% off each and round to two decimals.
const discounted = prices
  .filter((p) => p > 10)
  .map((p) => (p * 0.8).toFixed(2));

console.log(discounted);
// toFixed returns text. To calculate with the result, turn it back into numbers:
console.log(discounted.map(Number));
Recorded output$ node discounts.js
[ '10.00', '24.00', '12.00' ]
[ 10, 24, 12 ]

Exercise 10.5 · Challenge

Add a function applyNightShow(price, hour) to the kiosk (1 cheaper from 22:00, never below 0), give each visitor an hour, and use the new function in receiptLine.
The book's short answer
function applyNightShow(price, hour) { return hour >= 22 ? Math.max(price - 1, 0) : price; }, called on the result of applyMemberDay.
Show the solution
kiosk.js⤓ File
// kiosk.js from the chapter, with a night show rule and an hour for each visitor.
function ticketPrice(age) {
  if (age < 4) return 0;
  if (age < 13 || age >= 65) return 6;
  return 10;
}

function applyMemberDay(price, isMember, day) {
  if (isMember && day === "Tuesday") {
    return price / 2;
  }
  return price;
}

// 1 cheaper from 22:00, and never below 0.
function applyNightShow(price, hour) {
  return hour >= 22 ? Math.max(price - 1, 0) : price;
}

function receiptLine(visitor) {
  const base = ticketPrice(visitor.age);
  const member = applyMemberDay(base, visitor.member, "Tuesday");
  const price = applyNightShow(member, visitor.hour);
  return `${visitor.name} (${visitor.hour}:00): ${price}`;
}

const visitors = [
  { name: "Sara", age: 34, member: true, hour: 22 },
  { name: "Adam", age: 9, member: false, hour: 18 },
  { name: "Huda", age: 70, member: true, hour: 23 },
  { name: "Yusuf", age: 2, member: false, hour: 22 },
];

for (const visitor of visitors) {
  console.log(receiptLine(visitor));
}
Recorded output$ node kiosk.js
Sara (22:00): 4
Adam (18:00): 6
Huda (23:00): 2
Yusuf (22:00): 0