Chapter 4 of 34
~11 minFunctions
Functions are reusable blocks of code that take input, do something, and (usually) return output. JavaScript gives you several ways to define them, each with slightly different behavior worth knowing.
Function Declarations vs Expressions
A function declaration (`function greet() {}`) is hoisted entirely, meaning you can call it before its definition appears in the file. A function expression (`const greet = function () {}`) is just a variable holding a function value, and follows normal variable hoisting rules - you cannot call it before the assignment runs.
Try it yourself
Declaration vs expression<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Arrow Functions
Arrow functions (`(a, b) => a + b`) are a shorter syntax for function expressions. The key practical difference is `this`: arrow functions do not have their own `this` - they inherit it from the surrounding scope, which makes them especially handy inside callbacks and class methods. We will revisit this in the `this`/prototypes topic.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Parameters: Defaults and Rest
You can give a parameter a default value with `= someValue`, used whenever the argument is omitted or `undefined`. The rest parameter `...args` collects any remaining arguments into a real array, which is useful for functions that accept a variable number of inputs.
Try it yourself
Default values and rest parameters<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Return Values and IIFEs
A function that has no `return` statement returns `undefined` implicitly. An Immediately Invoked Function Expression (IIFE) - `(function () { ... })()` - defines and calls a function in one step, historically used to create a private scope before `let`/`const`/modules existed.
Coding challenge
Write an arrow function multiply that takes two numbers and returns their product, with the second parameter defaulting to 2. Call it once with one argument and once with two, logging both results.
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. Why can you call a function declaration before it appears in the file, but not a function expression?
2. What is the key practical difference between an arrow function and a regular function?
3. What does a rest parameter (`...args`) collect?
4. What does a function return if it has no explicit `return` statement?