JavaScript - Functions

Overview

Estimated time: 25–35 minutes

Functions are reusable blocks of code. Start with declarations, calling, and returning values.

Learning Objectives

  • Declare and call functions.
  • Return values and understand early returns.
  • Know where advanced topics fit (expressions, arrow, closures).

Prerequisites

Function declaration

function add(a, b) {
  return a + b;
}
const sum = add(2, 3); // 5

Early return

function safeDivide(a, b) {
  if (b === 0) return null;
  return a / b;
}

Common Pitfalls

  • Forgetting return when a value is needed; implicit undefined will result.

Checks for Understanding

  1. What is the difference between a function declaration and a function expression?
  2. What happens if a function finishes without a return statement?
Show answers
  1. Declarations are hoisted (available throughout their scope); expressions are evaluated at runtime and assigned to a variable.
  2. It returns undefined by default.

Exercises

  1. Write max(a,b) that returns the larger number.
  2. Write greet(name) that returns a string greeting.