Home > Web Front-end > JS Tutorial > Understanding Default Parameters in JavaScript Functions

Understanding Default Parameters in JavaScript Functions

Linda Hamilton
Release: 2024-12-23 10:44:29
Original
122 people have browsed it

Understanding Default Parameters in JavaScript Functions

Default Parameters in JavaScript Functions

Default parameters in JavaScript allow you to specify default values for function parameters. If the function is called without a value for a particular parameter, the default value is used instead.

This feature was introduced in ES6 (ECMAScript 2015) and helps to handle cases where a parameter may not be provided, avoiding undefined behavior and making your code more robust.

1. Basic Syntax of Default Parameters

In the following example, if no argument is passed for b, it will default to 10:

function sum(a, b = 10) {
  return a + b;
}

console.log(sum(5, 3));  // Output: 8
console.log(sum(5));     // Output: 15 (b defaults to 10)
Copy after login
Copy after login

In this case:

  • When sum(5, 3) is called, the result is 8 because b is explicitly passed as 3.
  • When sum(5) is called, the result is 15 because b is not passed, so it takes the default value of 10.

2. Using Default Parameters with Expressions

You can also set default values that are the result of expressions, such as calling a function or performing calculations.

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

greet();          // Output: Hello, Guest!
greet("John");    // Output: Hello, John!
Copy after login

Here, "Guest" is the default value for name if no value is passed to the function.

3. Default Parameters with Destructuring

Default parameters also work with destructuring. If you are using object or array destructuring in the function parameters, you can set default values for specific properties or items.

Default Values in Object Destructuring

function printInfo({ name = "Anonymous", age = 18 } = {}) {
  console.log(`Name: ${name}, Age: ${age}`);
}

printInfo({ name: "Alice", age: 25 });  // Output: Name: Alice, Age: 25
printInfo({});                          // Output: Name: Anonymous, Age: 18
printInfo();                            // Output: Name: Anonymous, Age: 18
Copy after login

In this case:

  • If the object is passed, the function uses the properties of that object.
  • If no object is passed or the object is missing properties, the default values are used.

Default Values in Array Destructuring

function printNumbers([a = 1, b = 2] = []) {
  console.log(`a: ${a}, b: ${b}`);
}

printNumbers([5, 10]);  // Output: a: 5, b: 10
printNumbers([7]);      // Output: a: 7, b: 2
printNumbers();         // Output: a: 1, b: 2
Copy after login

In this case:

  • The function works with an array and provides default values for a and b if no values are passed.

4. Default Parameters and Function Arguments

You can also use default parameters in conjunction with arguments to handle cases where the number of arguments is dynamic.

function multiply(a, b = 2) {
  console.log(a * b);
}

multiply(3, 4);  // Output: 12
multiply(3);     // Output: 6 (b defaults to 2)
Copy after login

In this example:

  • The function multiplies a by b, and if b is not provided, it defaults to 2.

5. Default Parameters with Functions that Return Defaults

You can use functions as default values, which can be helpful in scenarios where you need dynamic or complex default values.

function getUser(id, name = getDefaultName()) {
  console.log(`User ID: ${id}, Name: ${name}`);
}

function getDefaultName() {
  return "John Doe";
}

getUser(1);          // Output: User ID: 1, Name: John Doe
getUser(2, "Alice"); // Output: User ID: 2, Name: Alice
Copy after login

In this example:

  • If name is not provided, the function getDefaultName() is called, and its result is used as the default value.

6. Default Parameters with Rest Parameters

You can combine default parameters with rest parameters (...args) to handle scenarios where you don't know how many arguments a function might receive.

function sum(a, b = 10) {
  return a + b;
}

console.log(sum(5, 3));  // Output: 8
console.log(sum(5));     // Output: 15 (b defaults to 10)
Copy after login
Copy after login

In this case:

  • The separator parameter has a default value of , if not provided, and strings will collect all additional arguments passed to the function.

Conclusion

Default parameters in JavaScript make functions more flexible by allowing you to define default values for parameters that are missing or undefined. This feature improves code readability and helps prevent errors caused by missing arguments.

It can be combined with other features such as destructuring, rest parameters, and even function calls to create dynamic, concise, and maintainable functions.


Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

The above is the detailed content of Understanding Default Parameters in JavaScript Functions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template