Functions, Parameters, and Return Values
Functions are reusable blocks of code designed to perform a specific task. They prevent code repetition and keep your projects modular and maintainable.
1. Defining Functions
In JavaScript, there are two primary ways to define a standard function: Function Declarations and Function Expressions.
A. Function Declarations
Defined using the function keyword followed by the function name.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"Function declarations are hoisted, meaning you can call them before they are declared in the code.
B. Function Expressions
Defined by assigning a function (often anonymous) to a variable.
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // 8Function expressions are not hoisted; you cannot call them before the line of declaration.
2. Parameters vs. Arguments
- Parameters: The variable placeholders listed in the function definition.
- Arguments: The real values passed to the function when it is called.
// 'x' and 'y' are parameters
function multiply(x, y) {
return x * y;
}
// 4 and 5 are arguments
multiply(4, 5); 3. Parameter Defaults and Rest Parameters
A. Default Parameters (ES6)
You can set fallback values for parameters in case they are missing or passed as undefined:
function welcomeUser(username = "Guest") {
console.log(`Welcome back, ${username}!`);
}
welcomeUser(); // "Welcome back, Guest!"
welcomeUser("Alice"); // "Welcome back, Alice!"B. Rest Parameters (...)
If you don't know how many arguments a function will receive, you can pack them into a single array parameter using the Rest operator (...):
function sumAll(...numbers) {
// 'numbers' is a real array
return numbers.reduce((sum, num) => sum + num, 0);
}
console.log(sumAll(1, 2, 3, 4)); // 10Note: The rest parameter must always be the last parameter in the list.
4. Return Values
A function execution stops as soon as it hits the return statement. The value after the return keyword is sent back to the caller.
function checkAge(age) {
if (age < 18) {
return "Minor";
}
return "Adult"; // Only runs if age >= 18
}If a function does not contain a return statement, it returns undefined by default.
In the next guide, we will learn about Arrow Functions and how they handle the this context differently.