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; implicitundefined
will result.
Checks for Understanding
- What is the difference between a function declaration and a function expression?
- What happens if a function finishes without a
return
statement?
Show answers
- Declarations are hoisted (available throughout their scope); expressions are evaluated at runtime and assigned to a variable.
- It returns
undefined
by default.
Exercises
- Write
max(a,b)
that returns the larger number. - Write
greet(name)
that returns a string greeting.