BeginnerJavaScript · Lesson 4 of 7

Functions & Scope

Function declarations, arrow functions, parameters and defaults, return values and scope.

Functions package steps under a name. Declare them with function name(params) { ... } or as arrow functions: const square = (n) => n * n. Arrow functions are short and are the usual choice for callbacks.

Parameters can have defaults (outOf = 100). A function without return gives back undefined. Functions are values: you can store them in variables and pass them to other functions.

Scope decides where a variable can be used. Variables declared with let/const inside { } exist only inside those braces. Keep variables in the smallest scope that works — it prevents accidental changes from elsewhere.

functions.jsJavaScript
function percentage(score, outOf = 100) {
  return Math.round((score / outOf) * 100);
}

const greet = (name, title) => (title ? `Hello, ${title} ${name}` : `Hello, ${name}`);

function applyToAll(values, fn) {          // a function that takes a function
  const out = [];
  for (const v of values) out.push(fn(v));
  return out;
}

console.log(percentage(42, 50));          // 84
console.log(greet("Amina"), "|", greet("Juma", "Mr."));
console.log(applyToAll([1, 2, 3], (n) => n * 10));   // [10, 20, 30]

const passMark = 30;                       // outer scope
function countPasses(scores) {
  let passes = 0;                          // only exists inside this function
  for (const s of scores) {
    if (s >= passMark) passes++;
  }
  return passes;
}
console.log(countPasses([82, 25, 49, 12]));   // 2
console.log(typeof passes);                   // "undefined": not visible out here
Runs in your browser · JavaScript

Key points

  • Arrow functions are compact and ideal for callbacks.
  • Default parameters replace manual "if missing" checks.
  • Declare variables in the smallest scope that works.

Exercise

Write areaOfRectangle(width, height) and areaOfCircle(radius). Then write describe(area, units = "cm") returning "Area: 12.00 cm²", and use applyToAll to describe a list of radii.

Show solution

Try the exercise yourself first — then compare your approach with this one.

Small single-purpose functions combine nicely: applyToAll maps each radius to an area, then to a description. The default units = "cm" means callers only pass units when they differ.

areas.jsJavaScript
const areaOfRectangle = (width, height) => width * height;
const areaOfCircle = (radius) => Math.PI * radius ** 2;
const describe = (area, units = "cm") => `Area: ${area.toFixed(2)} ${units}²`;

function applyToAll(values, fn) {
  const out = [];
  for (const v of values) out.push(fn(v));
  return out;
}

console.log(describe(areaOfRectangle(3, 4)));             // Area: 12.00 cm²
console.log(applyToAll([1, 2, 3], (r) => describe(areaOfCircle(r), "m")));
// [ 'Area: 3.14 m²', 'Area: 12.57 m²', 'Area: 28.27 m²' ]
Runs in your browser · JavaScript

Check your understanding

  1. What does a function return if it has no return statement?

  2. Which is a correct arrow function that doubles a number?

  3. A variable declared with let inside a function — where can it be used?

  4. What does it mean that functions are "values" in JavaScript?

Ask AI