MakeW3web

JavaScript Function Parameters and Default Values

In JavaScript, functions can accept parameters (also known as arguments) that allow you to pass values into the function. These values can then be used within the function to perform various tasks. You can also assign default values to function parameters, which are used when a parameter is not explicitly provided during the function call.

  1. Function Parameters:

Function parameters are the names of the values you expect to receive when the function is called. These names are listed inside the parentheses in the function definition, separated by commas.

Example:

function multiply(a, b) {
  return a * b;
}

const result = multiply(2, 3);
console.log(result); // Output: 6

In this example, the `multiply` function has two parameters, `a` and `b`. When the function is called with the arguments `2` and `3`, the values are passed to the function and used to calculate the product of `a` and `b`.

  1. Default Values:

In JavaScript, you can assign default values to function parameters. If a parameter is not provided when the function is called, its default value is used instead. Default values are assigned using the assignment operator (`=`) in the function definition.

Example:

function greet(name = "Friend") {
  console.log(`Hello, ${name}!`);
}

greet("John"); // Output: Hello, John!
greet(); // Output: Hello, Friend!

In this example, the `greet` function has a default value of `"Friend"` for the `name` parameter. When the function is called without any arguments, the default value is used, resulting in the output "Hello, Friend!".

Default values can be any valid JavaScript expression, including other functions. They are evaluated only if the parameter is missing or `undefined` in the function call.

Example:

function randomNumber() {
  return Math.floor(Math.random() * 10) + 1;
}

function randomGreeting(name = `Friend${randomNumber()}`) {
  console.log(`Hello, ${name}!`);
}

randomGreeting("Jane"); // Output: Hello, Jane!
randomGreeting(); // Output: Hello, FriendX! (where X is a random number between 1 and 10)

In this example, the `randomGreeting` function has a default value for the `name` parameter that includes a call to the `randomNumber` function. When the function is called without any arguments, the default value is used, resulting in a random greeting like "Hello, Friend3!".

Function parameters and default values help you write more flexible and reusable code. They enable your functions to work with different input values and provide sensible defaults when no arguments are provided, making your code more robust and easier to maintain.

Was this page helpful?