What Are Functions?
Functions are reusable blocks of code that perform a specific task. They help you avoid repetition and organize your code.
💡 Real-world analogy
Think of a function as a recipe. Once you have the recipe (the function), you can follow it (call the function) as many times as you want.
Function Declarations
The most common way to define a function. It's "hoisted" to the top of its scope.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // "Hello, Alice!"
Function Expressions
Assigning a function to a variable. These are not hoisted.
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Bob")); // "Hello, Bob!"
Arrow Functions
A shorter syntax introduced in ES6. Great for simple functions.
const greet = (name) => {
return "Hello, " + name + "!";
};
// Even shorter for single expressions
const double = x => x * 2;
console.log(double(5)); // 10
Parameters and Arguments
- Parameters — the variables listed in the function definition
- Arguments — the values passed when calling the function
function add(a, b) { // a and b are parameters
return a + b;
}
add(3, 5); // 3 and 5 are arguments
Return Values
The return statement sends a value back from the function. Without it, the function returns undefined.
function multiply(x, y) {
return x * y;
}
let result = multiply(4, 3); // result = 12
Common Mistakes
- Forgetting to use
return— the function returnsundefined - Confusing parameters with arguments
- Using arrow functions when you need
thisbinding (we'll cover this later)
Quick Quiz
1. What does the return statement do?
2. Which is NOT a way to define a function?
3. What is the output?
function test() { } console.log(test());
Summary
- Functions are reusable blocks of code
- Function declarations are hoisted; expressions are not
- Arrow functions provide a shorter syntax
- Parameters are placeholders; arguments are the actual values
returnsends a value back; without it, the function returnsundefined
