Parameters are variables that are declared in the definition of a function and act as “containers” for values that are passed to that function.
This allows functions to be much more reusable and versatile than if they could only always do the same thing.
The basic syntax of a function with parameters is as follows:
function functionName(parameter1, parameter2) {
// Function body
}
Let’s see a simple example,
function add(a, b) {
return a + b;
}
let result = add(5, 3); // result will be 8
In this case,
a
andb
are the parameters of the functionadd
.- When we call
add(5, 3)
, we are passing the values5
and3
as arguments to the function.
Types of parameters in JavaScript
In JavaScript, parameters can take different forms depending on how we define them. Let’s look at some of the most important types of parameters.
Positional Parameters
Positional parameters are the most common. They are those defined in the order in which they are expected to be passed when invoking the function.
The function automatically assigns the passed arguments to these parameters in the specified order.
function introducePerson(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
introducePerson("John", 30); // Output: Hello, my name is John and I am 30 years old.
Default Parameters
Default parameters allow us to define default values for a function’s parameters.
If an argument is not passed for a particular parameter, the default value undefined
will be used.
function greet(name = "guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, guest!
greet("Maria"); // Output: Hello, Maria!
In this case, if we do not provide a name when calling greet
, the parameter name
will take the value "guest"
.
REST Parameters
REST parameters allow a function to accept an indefinite number of arguments as an array.
They are defined using three dots (...
) before the parameter name.
function addAll(...numbers) {
return numbers.reduce((accumulator, number) => accumulator + number, 0);
}
console.log(addAll(1, 2, 3)); // Output: 6
console.log(addAll(10, 20, 30, 40)); // Output: 100
In this example, numbers
becomes an array containing all the arguments passed to the function.
Destructured Parameters
Destructured parameters allow us to decompose objects or arrays into individual parameters (this is useful for working with objects in functions).
For example, we can destructure objects.
function showData({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}
const person = { name: "Luis", age: 30 };
showData(person); // Output: Name: Luis, Age: 30
Or destructure arrays.
function showColors([color1, color2]) {
console.log(`First color: ${color1}, Second color: ${color2}`);
}
const colors = ["Red", "Blue"];
showColors(colors); // Output: First color: Red, Second color: Blue
Calling the function with more or fewer arguments
In JavaScript, when you call a function and pass more or fewer parameters than the function expects, the language does not automatically throw an error but handles this situation flexibly.
Let’s see what happens in both cases.
Fewer Arguments
If you do not provide a value for an expected parameter, that parameter will automatically have the value undefined
.
function greet(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
greet("Luis");
// Prints: Hello, my name is Luis and I am undefined years old.
More Arguments
When you provide more arguments than the function has defined as parameters, the extra values are not assigned to any parameter.
function add(a, b) {
return a + b;
}
console.log(add(2, 3, 4, 5));
// Prints: 5 (ignores the extra values 4 and 5).
This happens because JavaScript does not enforce that all parameters must be defined when calling a function.
This is a peculiarity of JavaScript. Is this a flaw or a virtue? I’ll let you decide (I vote a bit 50/50% 😅).
Practical Examples
Let’s look at some practical examples of how these types of parameters can be applied in real situations.
Discount Calculation
Imagine we are developing a function to calculate prices with discounts. We will use default parameters and REST parameters:
function calculatePrice(basePrice, ...discounts) {
let totalDiscount = discounts.reduce((accumulator, discount) => accumulator + discount, 0);
return basePrice - totalDiscount;
}
console.log(calculatePrice(100, 10, 5)); // Output: 85
Configuration Management
In an application, it’s common to handle configurations that may have default values. Here we use destructuring and default parameters:
function configureApp({ theme = "light", language = "es" } = {}) {
console.log(`Configuration: Theme - ${theme}, Language - ${language}`);
}
configureApp(); // Output: Configuration: Theme - light, Language - es
configureApp({ theme: "dark" }); // Output: Configuration: Theme - dark, Language - es