How to set the default value of a function?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #JS Basics #Functions

Short Answer

A default value for a function parameter is set directly in the function definition using the = operator:

function greet(name = "Guest") {
  console.log("Hello,", name);
}

If name is not passed — the value "Guest" will be used.


Why is this useful?

  • Avoid undefined when arguments are missing
  • Improve code readability
  • Simplify function calls with many parameters
  • Handle optional parameters more easily

Examples

1. Simple default value

function multiply(a, b = 1) {
  return a * b;
}
 
console.log(multiply(5)); // 5 (b will be 1)

2. Value can be an expression

function createUser(name, isAdmin = false) {
  return { name, isAdmin };
}

3. Using other parameters

function sum(a, b = a) {
  return a + b;
}
 
console.log(sum(3)); // 6

Key Features

  • The default value is calculated every time the function is called
  • Default values work only with undefined
  • Order matters: put regular parameters first, then defaults

Useful Pattern

function fetchData(url, options = {}) {
  const { method = "GET", cache = "no-cache" } = options;
  // ...
}

Conclusion

Default parameter values are a simple and powerful tool to make your functions more robust and convenient.
Use them to write cleaner and more resilient JavaScript code.