Functions
Understand functions, how to define them, pass arguments, and return values. Learn about scope and closures.
Function Arguments and Parameters in JavaScript Essentials
Introduction
This section explores how to pass arguments to functions and how to define parameters within the function definition. We'll also cover default parameters and rest parameters, crucial concepts for writing flexible and reusable JavaScript functions.
Understanding Arguments and Parameters
In JavaScript, functions are fundamental building blocks. They allow you to encapsulate reusable blocks of code. To make functions truly versatile, we often need to provide them with data to work with. This is where arguments and parameters come in.
Parameters
Parameters are the variables listed inside the parentheses `()` in the function definition. They act as placeholders for the values that the function expects to receive when it is called. Think of them as named slots waiting to be filled with data.
function greet(name) { // 'name' is a parameter
console.log("Hello, " + name + "!");
}
Arguments
Arguments are the actual values that are passed to the function when it is invoked (called). They are placed inside the parentheses `()` during the function call. The arguments are assigned to the corresponding parameters in the function definition.
greet("Alice"); // "Alice" is an argument passed to the 'greet' function
greet("Bob"); // "Bob" is another argument
In the examples above, `name` is the parameter in the `greet` function definition. "Alice" and "Bob" are arguments passed to the `greet` function when it is called.
Default Parameters
ES6 (ECMAScript 2015) introduced default parameters, which allow you to specify default values for parameters in a function definition. If an argument is omitted when the function is called, the parameter will take on its default value.
function greet(name = "Guest") { // 'Guest' is the default parameter value
console.log("Hello, " + name + "!");
}
greet("David"); // Output: Hello, David!
greet(); // Output: Hello, Guest! (name takes the default value)
In this example, if we call `greet()` without any arguments, the `name` parameter will default to "Guest".
Rest Parameters
Rest parameters, also introduced in ES6, allow you to represent an indefinite number of arguments as an array. They are denoted by three dots `...` followed by a parameter name. The rest parameter must be the last parameter in the function definition.
function sum(...numbers) { // 'numbers' is the rest parameter (an array)
let total = 0;
for (let number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
console.log(sum()); // Output: 0 (numbers is an empty array)
In this example, the `sum` function can accept any number of arguments, which are then collected into the `numbers` array. We can then iterate through the `numbers` array to calculate the sum.