JavaScript is the most popular programming language with various features to make it easier for us to work with it. One such feature is the ability to declare the optional function parameters. In this article, we will learn about the optional parameters and the different approaches to declaring them in JavaScript.
What are Optional Parameters in JavaScript?
While calling the function, we pass several parameters. But in some cases, some of the variables are not required. Instead of passing garbage values in place of them, we can use optional parameters.
Optional parameters in JavaScript are the function parameters that are not mandatory to pass when calling a function. We can assign default values to these variables, which can be used if no value or undefined is passed for those parameters.
In JavaScript, we define the parameters of a function within the parentheses of a function declaration. The parameters are by default considered mandatory. That is, we are required to pass a value for each of them. If we want to avoid providing the values of these variables while calling the function, we can use the optional parameters.
For example, Let’s say we have a function that calculates the area of a rectangle and a square. In the case of a square, we only need a single parameter, i.e. side of the square. While in the case of a rectangle length and breadth are required.
To use our function for both shapes, we can make the breadth parameter optional by providing it a default value of 1. Hence, it is needed to be used for squares, we can pass only 1 parameter, else 2 parameters for rectangles.
We can declare optional parameters using different methods. Let’s see them one by one.
1) Using the Default Value Approach
The simplest way to declare optional parameters is by providing the default values to them. This default value will be used if no value or undefined is passed for the parameters. We can provide the default values by using the assignment operator (=) in the function definition.
Let us see an example of the same:
// Defining a function with optional parameters function greet(name = "user") { console.log(`Hello ${name}, Welcome to favtutor!`); } // Not providing the value of optional parameters greet(); // Providing the value of optional parameters greet("Joy");
Output:
Hello user, Welcome to favtutor!
Hello Joy, Welcome to favtutor!
In the above function, we have made the name parameter the optional parameter by simply assigning it the value of “user”. Now, we can provide the name in function calls or skip it.
Rule for Declaring the Optional Parameters
We need to follow a rule while declaring the optional parameters using this approach. The optional parameters with default values should come after the required parameters. In the function definition, we should first write the required parameters that do not have any default values, and then the parameters with the default values.
We can understand it better with an example:
// Defining a function with optional parameters function sendMessage(sender, message = 'Default message') { console.log(`Message from ${sender}: ${message}`); } // Not Providing the value of optional parameters sendMessage("John"); // Providing the value of optional parameters sendMessage("John", "Hello Roy")
Output:
Message from John: Default message
Message from John: Hello Roy
As we can see in the above example, we have first written the parameter sender as it is the required parameter, and then the second parameter message. This works fine.
But, what if we first write the optional parameter and then the required parameter? Let’s try and run our code.
// Defining a function with optional parameters function sendMessage(message = 'Default message', sender) { console.log(`Message from ${sender}: ${message}`); } // Not Providing the value of optional parameters sendMessage("John"); // Providing the value of optional parameters sendMessage("Hello Roy", "John");
Output:
Message from undefined: John
Message from John: Hello Roy
We can see that when we first called the function without providing the value for the default parameter, it printed undefined in place of it.
2) Using the Arguments Variable
When compared to the above method, it is a complex one. Instead of providing default values in the function definition, we will check for the values of the arguments passed. This can be done using the implicit arguments variable.
Every function has access to this arguments variable, which holds an array-like object containing the values of all the arguments passed to the function. We can simply check the length of the arguments object to know the number of arguments passed and with help of it, we can handle the optional parameters.
Let’s check an example of it:
// Defining a function with optional parameters function sum(a, b) { if (arguments.length === 0) { // If no argument is passed return 0; } else if (arguments.length === 1) { // If single argument is passed return a; } else { // If both the arguments are passed return a + b; } } // Not passing values for any parameter console.log(sum()); // Passing value for first parameter only console.log(sum(5)); // Passing values for both the parameters console.log(sum(2, 3));
Output:
0
5
5
In this example, we have checked the length of the argument object and used it to find the number of parameters passed to the sum function. According to different cases, we have returned the result of the function.
Conclusion
The Optional Parameters in JavaScript is a powerful feature that allows us to define the default values for functional parameters. This feature simplifies the code and provides us flexibility while calling the functions. Another great feature you need to learn is the Arrow function in JavaScript, which is very important for beginners to master.