# Why use default parameters in JavaScript functions?

Function in programming is a block of code that performs a specified task. You define them once and can call them(using a name in most cases) wherever you want to perform that task.

JavaScript is no different. In JavaScript, one of the popular ways to define(or declare) a function using the `function` keyword, a meaningful name, a pair of parenthesis, and followed by a pair of curly braces where you define the tasks/instructions.

```javascript
function doSomething() {
    // Instrauction to do something.
}
```

Optionally, you can pass one more parameter to a function.

```javascript
// Define a function add with two parameters
function add(x, y) {
    return x + y;
}

// Invoke/Call the function passing the actual values
add(2, 3); // It returns the number 5
```

## Parameter vs Argument in JavaScript Function

Like other programming languages, JavaScript also has some terms and jargon for you to get confused. One of them is `Parameter` vs `Argument`.

* `Parameters`: These are the variables we define when we declare a function.
    
* `Arguments`: These are the values we pass to a function when we invoke/call the function.
    

The code snippet below demonstrates the difference with an example.

![parameter vs arguments](https://cdn.hashnode.com/res/hashnode/image/upload/v1698577053782/e58e6dae-7d40-49f9-8715-ba7b42e9f300.png align="center")

> Did you know I share knowledge and tips like these on [X](https://twitter.com/tapasadhikary) and [LinkedIn](https://www.linkedin.com/in/tapasadhikary/)? Connect with me if you do not want to miss them.

## How to set default function parameters in JavaScript?

The default function parameters allow you to initialize a parameter with a default value. You can use the equal sign(=) and the value to initialize a parameter while declaring the function.

```javascript
// Here the message paramater is a `default function parameter`
// as we initialize it with a default value.
function greetMe(name, message="Hello") {
    return `${message} ${name};`
}

// When we do not pass a value for the message,
// The default value is used.
greetMe("tapaScript"); // Hello tapaScript

// When we pass a value for the message,
// The passed value override the defaule value.
greetMe("tapaScript", "Hola"); // Hola tapaScript
```

In the above code, the `greetMe` function takes two parameters `name` and `message`. The `message` parameter is a `default function paramater` as we initialize it with a default value.

When we do not pass a value for the `message`, the default value is used. But, when a value is passed, the passed value is used by overriding the default value.

Note that if you pass an `undefined` for the default parameter, it will take the default value.

```javascript
console.log(greetMe("tapaScript", undefined)); // Hello tapaScript
```

## Use case 1: Safeguard function's return value

Consider a situation where you perform some arithmetic operation in a function, like taking two numbers as parameters and returning the double of their addition.

```javascript
// A functiont to sum up two numbers
// and return the double of it.
function calc(a, b) {
    return (2 * (a + b));
}
```

When you pass arguments for both parameters, the function outputs the desired result.

```javascript
calc(2,3); // Output is 10
```

However, when you miss out on one (say, the second one), the output may not be the desired one.

```javascript
calc(2);
```

In this case, the output is,

```bash
NaN # That is Not a Number
```

It is because we were trying to add `undefined` to a number. You could fix it by adding checks within the function. If the parameter `b` is `undefined`, handle it in some way, may consider the value of `b` as `0`.

```javascript
if(!b) {
 b = 0;
}
```

That's an unnecessary condition when you can do the same with the default function parameter. You can set the initial value of `b` with `0`.

```javascript
function calc(a, b=0) {
    return (2 * (a + b));
}
```

Great! Now, if you miss out on passing the value for `b`, the function considers the value of it as `0` , and the output is a much more predictable one.

```javascript
calc(2); // Output is 4
```

You can do the same for both parameters.

```javascript
function calc(a=0, b=0) {
    return (2 * (a + b));
}
```

The output when someone calls the `calc()` function without passing any arguments.

```javascript
calc(); // Output is 0. Better than a NaN
```

## Use case 2: Construct default parameter from existing parameters

You can construct the value of the default function parameter from the existing parameter's value.

```javascript
function sayGood(name, gender, message=`${name} is a good ${gender}`) {
    return message;
}
```

In the example code above, we have initialized the message parameter with a value which is constructed by the other two former parameters `name` and `gender`. So when you invoke the `sayGood` function with the value of name and gender, it will return a well-constructed `message` value accordingly.

```javascript
sayGood('Alex', 'Boy'); // Alex is a good Boy
sayGood('Emilie', 'Girl'); // Emilie is a good Girl
```

## Use case 3: Setting an empty array as the default value for the destructured parameter

You can set an empty array or object as the default value for the destructured function parameters.

```javascript
function emp([dept = 'Manager', salary = 2000] = []) {
  return `${dept} gets ${salary}`;
}
```

The method `emp` sets up an empty array as the default value for the destructured parameters, `dept` and `salary`. So, when you pass an empty array to the function, it will take the default values for the dept and salary.

```javascript
emp([]); // Manager gets 2000
```

You can override default values by passing the new value as an array element.

```javascript
emp(['Employee']); // Employee gets 2000
```

Another example,

```javascript
emp(['Employee', 1500]); // Employee gets 1500
```

## A few more things to note about the default parameters

JavaScript's default function parameters are amazing, isn't it? Let's talk about a few more important aspects you need to keep in mind. These are important for the interviews as well 🥹.

### Arguments for the default parameters get evaluated at the call time

Consider this code snippet,

```javascript
function tryThis(value, arr = []) {
  arr.push(value);
  return arr;
}
```

Now, let's call the `tryThis` function with an argument:

```javascript
tryThis('😊');
```

By now, you can guess the output. Yes, it will be,

```bash
['😊']
```

Fair enough. But what if we invoke the `tryThis` function again(the second time) with an argument,

```javascript
tryThis('🥹');
```

What will be the output of the second time call?

1. \['😊'\]
    
2. \['😊', '🥹'\]
    
3. \['🥹'\]
    

The answer is #3, `['🥹']`.

It is because every time we invoke the `tryThis` function, a new instance of the array `arr` will be created. Thus, when we call the function a second time, the previous instance of `arr`(with '😊') has been destroyed, and a new one has been created with the argument('🥹') we passed.

### The default parameter value and the function's scope

You can not use anything from the function body as an initializer for the default parameter.

```javascript
function fx(t = task()) {
    function task() {
        // Do Something...
    }
}
```

In the above code snippet, we are trying to use the `task()` function as an initializer for the parameter `t`. This is not allowed. We will get a `ReferenceError`.

```javascript
fx(); // ReferenceError: task() is not defined
```

## Hold on, here is something more for you...

Do you want to learn more about JavaScript functions from a well-structured crash course? Yes, it is available for FREE. Check it out.

> %[https://www.youtube.com/watch?v=UPeFK1uFJCE] 
> 
> Don't forget to [SUBSCRIBE](https://www.youtube.com/tapasadhikary?sub_confirmation=1) to tapaScript for the future content 😊

---

## **Before We End...**

That's all. Thanks for reading it. I hope it was insightful. If you liked the tutorial, please post likes and share it in your circles.

Let's connect. I share web development, content creation, Open Source, and career tips on these platforms.

* [**tapaScript on YouTube**](https://www.youtube.com/tapasadhikary?sub_confirmation=1)
    
* [**X(eka Twitter)**](https://twitter.com/tapasadhikary)
    
* [**LinkedIn**](https://www.linkedin.com/in/tapasadhikary/)
    
* [**GitHub**](https://github.com/atapas)
