Functions: Declarations, Expressions & Arrows
The building blocks of JavaScript. Learn the three ways to write functions, how they receive data, and how they return results.
What is a function?
A function is a reusable block of code designed to perform a particular task. You define it once, and you can 'call' or 'invoke' it as many times as you want.
Functions take inputs (called parameters), do some work, and then output a result (via the return keyword).
The three ways to write them
1. **Function Declarations**: function add(a, b) { ... }. These are 'hoisted', meaning you can call them before they appear in the code.
2. **Function Expressions**: const add = function(a, b) { ... }. Here, the function is anonymous and assigned to a variable. It is not hoisted.
3. **Arrow Functions**: const add = (a, b) => { ... }. Introduced in ES6, these are shorter and have special rules regarding the this keyword (which we will cover in advanced topics).
Parameters vs. Arguments
These terms are often mixed up, but they mean different things.
**Parameters** are the variables listed in the function's definition. For example, in function greet(name), name is the parameter.
**Arguments** are the actual values you pass to the function when you call it. In greet('Alice'), 'Alice' is the argument. The argument binds to the parameter when the function runs.
The Function Flow
Watch how arguments flow into a function's parameters, get processed, and then flow back out via the return statement.
The Data Flow
Under the hood
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Function Declarations are hoisted; Expressions and Arrow Functions are not.
- Parameters are the names in the definition; Arguments are the values passed during the call.
- Functions without a
returnstatement implicitly returnundefined. - Arrow functions offer a concise syntax and can implicitly return values if written on one line.
Done with this concept?
Mark it complete to track your progress. No login needed.