Functions
What Are Functions?
A function is like a recipe card. You write the instructions once, give it a name, and then you can "cook" that recipe anytime by calling its name. You can also pass in ingredients (called parameters) and get back a finished dish (the return value).
Functions are the backbone of JavaScript. They help you:
- Avoid repetition — write once, use everywhere
- Organize code — break big problems into small, named pieces
- Create abstractions — hide messy details behind a clean name
There are three main ways to create functions in JavaScript: declarations, expressions, and arrow functions.
Three Ways to Create Functions
Parameters — Default Values & Rest
Default parameters let you set a fallback value in case the caller doesn't provide one. It's like a restaurant that brings you water automatically unless you order something else.
Rest parameters (...args) collect any number of arguments into an array. Super useful when you don't know how many inputs you'll get.
Default & Rest Parameters
Functions Are Values — Passing Them Around
In JavaScript, functions are first-class values. That means you can store them in variables, pass them as arguments to other functions, and return them from functions. This is what makes JavaScript so flexible.
A function that takes another function as an argument (or returns one) is called a higher-order function. Each function call gets pushed onto the call stack. You'll see these everywhere — setTimeout, addEventListener, array methods like .map() and .filter().