JavaScript Function Parameters (original) (raw)
Last Updated : 17 Dec, 2024
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. JavaScript ``
function greet(name) {
return Hello, ${name}!
;
}
console.log(greet("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.
JavaScript `
function add(a, b) { return a + b; } console.log(add(5, 3)); console.log(add(5));
`
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.
JavaScript `
function mul(a, b = 1) {
return a * b;
}
console.log(mul(5));
console.log(mul(5, 2));
`
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.
JavaScript `
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4));
`
4. Destructured Parameters
You can destructure arrays or objects passed as arguments into individual variables.
JavaScript ``
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.
JavaScript ``
function executeTask(task, callback) {
console.log(Task: ${task}
);
callback();
}
executeTask("Clean the room", () => {
console.log("Task Completed!");
});
``
Output
Task: Clean the room Task Completed!