Articles by FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
Articles by FavTutor
No Result
View All Result
Home Web Developement

Declaring Optional Parameters in Javascript (with code)

Komal Bhatia by Komal Bhatia
January 2, 2024
Reading Time: 5 mins read
Optional parameters in javascript
Follow us on Google News   Subscribe to our newsletter

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.

ShareTweetShareSendSend
Komal Bhatia

Komal Bhatia

I am a dedicated Computer Science student with a strong track record of academic excellence. I am a highly motivated individual with a passion for providing creative and innovative solutions to complex problems. I possess skills in the domain of C++ and web development and am always eager to contribute to the field of Software Development.

RelatedPosts

Javascript Animation Libraries

Top 10 JavaScript Animation Libraries in 2025

February 19, 2025
JavaScript Interview Questions

Top 40 JavaScript Interview Questions and Answers in 2024

April 1, 2025
Best React UI Component Libraries

10 Must-Know React UI Component Libraries for Web Devs 2024

May 7, 2024
Currying in JavaScript

Currying in JavaScript Explained (with Examples)

March 15, 2024
Javascript Format Currency

Javascript Program for Format Currency

April 8, 2025

About FavTutor

FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.

Categories

  • AI News, Research & Latest Updates
  • Trending
  • Data Structures
  • Web Developement
  • Data Science

Important Subjects

  • Python Assignment Help
  • C++ Help
  • R Programming Help
  • Java Homework Help
  • Programming Help

Resources

  • About Us
  • Contact Us
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.

No Result
View All Result
  • AI News
  • Data Structures
  • Web Developement
  • AI Code Generator
  • Student Help
  • Main Website

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.