Default Parameters

In JavaScript, default parameters allow you to initialize named parameters with default values if no value or undefined is passed. This feature was introduced in ES6 (ECMAScript 2015) and helps in making your functions more robust and readable.

Syntax

The syntax for default parameters is straightforward. You simply assign a default value to the parameter directly in the function signature.

default-parameters-basic.js
function greet(name = "Guest") {
  return `Hello, ${name}!`;
}

console.log(greet()); // "Hello, Guest!"
console.log(greet("Hunter")); // "Hello, Hunter!"

Multiple Default Parameters

You can also have multiple default parameters in a single function. Each parameter can be assigned a default value.

default-parameters.js
function createUser(name = "Anonymous", age = 18, country = "Unknown") {
  return `Name: ${name}, Age: ${age}, Country: ${country}`;
}

console.log(createUser()); // "Name: Anonymous, Age: 18, Country: Unknown"
console.log(createUser("Amy", 25, "USA")); // "Name: Amy, Age: 25, Country: USA"

Using Expressions as Default Values

Default values can also be the result of an expression, including function calls.

default-values.js
function getDefaultAge() {
  return 21;
}

function createUser(name = "Anonymous", age = getDefaultAge()) {
  return `Name: ${name}, Age: ${age}`;
}

console.log(createUser()); // "Name: Anonymous, Age: 21"
console.log(createUser("Bob", 30)); // "Name: Bob, Age: 30"

Interdependent Default Parameters

Default parameters can reference parameters that appear earlier in the parameter list.

interdependent-params.js
function createMessage(name, greeting = `Hello, ${name}`) {
  return greeting;
}

console.log(createMessage("Alice")); // "Hello, Alice"
console.log(createMessage("Bob", "Hi there!")); // "Hi there!"

Practical Examples

API Request Function

Consider an API request function where certain parameters have sensible defaults.

api-ex.js
function fetchData(url, method = "GET", timeout = 5000) {
  console.log(`Fetching data from ${url} with method ${method} and timeout ${timeout}`);
  // Imagine an actual fetch request here
}

fetchData("https://api.example.com/data"); 
// Fetching data from https://api.example.com/data with method GET and timeout 5000

fetchData("https://api.example.com/data", "POST", 10000); 
// Fetching data from https://api.example.com/data with method POST and timeout 10000

Event Handler

A function to add an event listener with default options.

event-handler.js
function addClickListener(element, callback, useCapture = false) {
  element.addEventListener("click", callback, useCapture);
}

const button = document.querySelector("button");
addClickListener(button, () => alert("Button clicked!"));

Common Errors and Best Practices

Avoid Overwriting Undefined Values

Be cautious of cases where undefined might be intentionally passed.

common-errors.js
function process(value = 10) {
  return value;
}

console.log(process()); // 10
console.log(process(undefined)); // 10
console.log(process(null)); // null (null is a valid value, not undefined)

Avoid Side Effects in Default Parameters

Default parameters should be free of side effects to avoid unexpected behaviors.

common-errors.js
let counter = 0;

function increment(count = ++counter) {
  return count;
}

console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment(10)); // 10
console.log(increment()); // 3 (side effect, counter is incremented even if count is provided)

Notes

  • Default Parameters were introduced in ES6 and allow for more flexible and robust function definitions.
  • Undefined Values are treated as missing parameters and default values are applied.
  • Expressions as Defaults can be useful but be cautious of side effects.
  • Interdependent Parameters can reference earlier parameters, allowing for more dynamic defaults.

FAQ

Q: Can default parameters be objects or arrays?

A: Yes, default parameters can be any valid JavaScript value, including objects and arrays.

Q: What happens if I pass undefined to a function with a default parameter?

A: If undefined is explicitly passed, the default value is used. If null is passed, it is treated as a valid value and the default is not used.

Q: Are default parameters evaluated every time the function is called?

A: Yes, default parameters are evaluated at the time the function is called, not when the function is defined.