Skip to main content

Function Parameters

JavaScript function parameters are the variables that are declared within the parentheses of a function declaration or function expression.

They are used to pass values into a function when it is called and provide a way for functions to receive input data and operate on it.

Function parameters are local to the function, meaning they are only accessible within the function's scope.

Here's an example of a function declaration with parameters:

function greet(name, greeting) {
console.log(greeting + ", " + name + "!");
}

greet("Alice", "Hello"); // "Hello, Alice!"

In this example:

  • The greet function has two parameters: name and greeting.
  • When the function is called with arguments "Alice" and "Hello", the values are passed to the respective parameters, and the function uses them in the function body to produce the output.

Default Parameters

JavaScript also allows for default parameter values, which are used when a parameter is not provided in a function call.

Here's an example:

function greet(name, greeting = "Hello") {
console.log(greeting + ", " + name + "!");
}

greet("Alice"); // "Hello, Alice!"

In this example:

  • The greeting parameter has a default value of "Hello".
  • If a value for greeting is not provided in the function call, the default value will be used.

Function Rest Parameter

JavaScript also supports rest parameters, which allow a function to accept a variable number of arguments as an array.

Here's an example:

function sum(...numbers) {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}

console.log(sum(1, 2, 3, 4, 5)); // 15

In this example:

  • The ...numbers syntax indicates a rest parameter, which collects any number of arguments passed to the function as an array called numbers.
  • The function can then operate on the array of arguments as needed.

The Arguments Object

The arguments object can be used to access the values of the arguments passed to a function, even if the function was called with a variable number of arguments or no arguments at all.

It provides a way to access the values dynamically, without explicitly declaring function parameters.

Here's an example of using the arguments object in a function:

function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}

console.log(sum(1, 2, 3, 4, 5)); // 15

In this example:

  • The sum function does not have any declared parameters.
  • Instead, it uses the arguments object to access the values of the arguments passed to the function.
  • The arguments object behaves like an array, with a length property and numerical indices, allowing you to loop through its elements to perform operations.