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.

function greet(name) { return Hello, ${name}!; } console.log(greet("Meeta"));

``

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!