JavaScript Function Parameters
Function parameters are variables defined in the function declaration that receive values (arguments) when the function is called. They play a key role in making functions reusable and dynamic.
- Values are assigned to parameters in the order they are passed.
- You can assign default values to parameters if no arguments are provided.
- Allows capturing an indefinite number of arguments into an array.
- Primitive types are passed by value, whereas objects are passed by reference.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Meeta"));
Output
Hello, Meeta!
- Parameter: name in the function definition.
- Argument: "Meeta" passed when calling the function.
Types of Parameters in JavaScript
1. Required Parameters
These are the basic parameters expected by the function. If not provided, they will be undefined.
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
console.log(add(5));
Output
8 NaN
2. Default Parameters
Introduced in ES6, default parameters allow you to assign a default value to a parameter if no argument is passed or if the argument is undefined.
function mul(a, b = 1) {
return a * b;
}
console.log(mul(5));
console.log(mul(5, 2));
Output
5 10
3. Rest Parameters
Rest parameters allow a function to accept an indefinite number of arguments as an array. Use the ... syntax to capture all additional arguments.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
Output
10
4. Destructured Parameters
You can destructure arrays or objects passed as arguments into individual variables.
function displayUser({ name, age }) {
return `${name} is ${age} years old.`;
}
const user = { name: "Meeta", age: 25 };
console.log(displayUser(user));
Output
Meeta is 25 years old.
5. Passing Functions as Parameters (Higher-Order Functions)
Functions in JavaScript can accept other functions as parameters, making it easy to create reusable code.
function executeTask(task, callback) {
console.log(`Task: ${task}`);
callback();
}
executeTask("Clean the room", () => {
console.log("Task Completed!");
});
Output
Task: Clean the room Task Completed!