How to use JavaScript Optional Parameters? [SOLVED]


JavaScript

Introduction

As a developer, there are situations where the function we create have parameters that might have default values we can. In such situations, JavaScript allows us to define optional parameters to deal with them. These default values are used when we don’t explicitly specify a parameter value.

Optional parameters are a feature in JavaScript that allow function arguments to be set to a default value if no value or undefined is passed to the function. This can be useful in cases where a function may be called with missing arguments, or when a function is called with arguments that are undefined.

In this article, we will discuss how to create optional parameters in JavaScript.

 

Examples using optional parameters

Using default value for optional parameters

To define an optional parameter in a JavaScript function, you simply assign a default value to the parameter in the function definition. For example:

function greet(name = "user") {
    console.log(`Welcome to GoLinuxCloud, ${name}! Here we have fun and learn`);
}

In this example, the name parameter is set to a default value of 'user'. If no value is passed to the greet function, it will use the default value. However, if a value is passed to the function, it will use that value instead of the default.

Here's an example of how you might use the above greet() function. In the first statement, we will not pass any parameter, however, for the second statement, we will pass a parameter.

greet();
greet("Danielle");

Output

Welcome to GoLinuxCloud, user! Here we have fun and learn
Welcome to GoLinuxCloud, Danielle! Here we have fun and learn

 

Using optional parameters with destructuring

You can also use optional parameters with destructuring syntax in the function definition. For example:

function greet({ name = "user", company = "GoLinuxCloud" } = {}) {
    console.log(`Welcome to ${company}, ${name}! Here we have fun and learn`);
}

greet();
greet({ name: "Danielle" });
greet({ name: "Danielle", company: "Workline" });

Output

Welcome to GoLinuxCloud, user! Here we have fun and learn
Welcome to GoLinuxCloud, Danielle! Here we have fun and learn
Welcome to Workline, Danielle! Here we have fun and learn

In this example, the name and company parameters are both optional. If no arguments are passed to the greet function, it will use the default values for both parameters. If an object is passed to the function, it will destructure the object and use the values for name and company if they are present, or the default values if they are not.

It's important to note that optional parameters must always be the last parameters in a function definition. This is because all parameters after the first optional parameter are also considered optional.

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

greet();
greet("Hi");
greet(undefined, "John");

Output

Hello, user!
Hi, user!
Hello, John!

In this example, both the greeting and name parameters are optional. However, if you call the greet function with only one argument, it will be assigned to the greeting parameter, and the name parameter will use the default value.

In another example, we can have one optional parameter among a list of parameters. Here, we accept three parameters but have only one to be optional.

function calc(avg, quotient, index = 2) {
    console.log((avg * quotient) ** index);
}

calc(23, 2.45);
calc(23, 2.45, 3);

Output

3175.3225
178929.42287500002

The calc function takes two argument in the first function call, and the index parameter is set as 2. For the second function call, we pass all three parameters, and therefore, the index parameter becomes what we pass, 3.

 

Using arguments.length property for optional parameters

In another approach, you can use the arguments.length property to determine the number of arguments passed to a function. This can be useful for handling optional arguments in your function.

For example, consider the following function that takes two arguments and use the logical OR operator to set default values.

function greet(name, greeting) {
    greeting = greeting || "Hello";
    console.log(greeting + ", " + name);
}

greet("Femi", "Good Evening");
greet("Femi");

Output

Good Evening, Femi
Hello, Femi

In this function, the greeting argument is optional. If no greeting is provided, the default value of 'Hello' is used. To determine if the optional argument was provided, you can check the arguments.length property and combine it with the logical OR property we used earlier.

function greet(name, greeting) {
    if (arguments.length === 2) {
        console.log(greeting + ", " + name);
    } else {
        console.log("Hello" + ", " + name);
    }
}

greet("Femi", "Good Evening");
greet("Femi");

Output

Good Evening, Femi
Hello, Femi

You can also use the arguments.length property to handle a variable number of arguments. For example:

function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}

console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4, 5));

Output

6
15

In this example, the sum function takes a variable number of arguments and returns the sum of all the arguments. The arguments.length property is used to loop through all the arguments and add them up.

 

Summary

Optional parameters can be a useful tool for simplifying function calls and providing default values for arguments. They can also make your code more readable by reducing the need for conditionals to check for missing arguments.

 

References

Default parameters - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment