JavaScript Program to Set a Default Parameter Value For a Function

Updated on December 19, 2024
Set a default parameter value for a function header image

Introduction

In JavaScript, functions are fundamental building blocks of code, allowing you to encapsulate and execute repetitive tasks efficiently. A common scenario is needing to set default values for parameters to ensure the function behaves predictably even if some inputs are omitted during the call. Setting default values can simplify function usage and make your code more resilient to errors caused by missing arguments.

In this article, you will learn how to set a default parameter value for a function in JavaScript through practical examples. Discover how to define defaults, understand their scope, and see how they can help prevent errors in your programs.

Setting Default Parameter Values in JavaScript

JavaScript from ES6 (ECMAScript 2015) onwards provides a straightforward syntax for setting default values directly in the function declaration. This feature makes your code cleaner and more intuitive.

Basic Default Parameter Example

  1. Define a function with a default parameter value.

  2. Call the function to observe how default values operate when arguments are omitted.

    javascript
    function greet(name = 'Visitor') {
        console.log(`Hello, ${name}!`);
    }
    
    greet(); // Output: Hello, Visitor!
    greet('Alice'); // Output: Hello, Alice!
    

    This example sets Visitor as the default value for name. If no argument is provided when greet() is called, name defaults to 'Visitor'.

Using Default Parameters with Multiple Arguments

  1. Extend the use of default parameters to functions with multiple parameters.

  2. Observe how JavaScript handles defaults when some arguments are still provided.

    javascript
    function orderCoffee(type = 'regular', size = 'medium') {
        console.log(`Order placed: ${size} ${type} coffee`);
    }
    
    orderCoffee(); // Output: Order placed: medium regular coffee
    orderCoffee('espresso'); // Output: Order placed: medium espresso coffee
    

    The function orderCoffee defines defaults for both type and size. If you provide one argument, JavaScript assigns it to type, and size uses its default value.

Dynamic Defaults Based on Other Parameters

  1. Use parameters as defaults for other parameters in the same function.

  2. Test how dynamic evaluation of default parameters works.

    javascript
    function calculateTotal(price, tax = price * 0.05) {
        console.log(`Total: ${price + tax}`);
    }
    
    calculateTotal(100); // Output: Total: 105
    calculateTotal(100, 20); // Output: Total: 120
    

    Here, the default value for tax is dynamically calculated as 5% of price. If tax is not specified, it uses this calculated value.

Default Parameters with Function Calls

  1. Introduce a function call as the default value for a parameter.

  2. Demonstrate how this setup can be useful for more complex initializations.

    javascript
    function getDefaultName() {
        return 'Guest';
    }
    
    function sayHello(name = getDefaultName()) {
        console.log(`Hello, ${name}!`);
    }
    
    sayHello(); // Output: Hello, Guest!
    sayHello('John'); // Output: Hello, John!
    

    This snippet uses a function getDefaultName() to provide a more complex default value. If no name is passed to sayHello, it calls getDefaultName() to obtain the default.

Conclusion

Leveraging default parameter values in JavaScript functions brings robustness and flexibility to your code. It ensures that functions behave predictably when expected inputs are missing and reduces the necessity for error-handling related to undefined values. Utilize default parameters to simplify your function calls, making your scripts more readable and easier to maintain. As demonstrated, the ability to set default values directly in the function signature enhances the functionality and adaptability of your JavaScript code.