Understanding JavaScript Default Parameters - Behind the Abstraction
Tags: javascript, webdev, learning, beginners
Published: 2019-06-26 17:19:06

MDN describes Default parameters as:
*Default function parameters allow __named parameters__ to be initialized with __default values__ if no value or undefined is passed.* 😕

Definition can be rephrased as:
If no value or `undefined` is passed to a __parameter__, use the __default value__. 😌

Before building custom Default parameters, let's get familiar with few of the terms mentioned in the definition.

## Parameter

Parameter is a name given to an argument passed while invoking a function.

```javascript
function greeting(username) {
  return `Hi ${username}!`;
}

greeting('Bruce'); // Hi Bruce!
```

In this example, parameter `username` is a name given to argument `'Bruce'`.

👩‍🏫 __Question Time:__ What will the function return if we do not pass any value to parameter `username` while invoking it?

```javascript
function greeting(username) {
  return `Hi ${username}!`;
}

greeting(); // Hi undefined!
```

__Answer:__ It will return `Hi undefined!`.

__Reason:__ JavaScript uses `undefined` as a default value if we don't pass any value to a parameter.
In our case, since we did not pass any value to `username` parameter, JavaScript assigned it `undefined` value and returned `Hi undefined!`.


So how can we avoid `undefined` case?

## Default value

ES6 introduced Default parameters for such scenarios.

```javascript
function greeting(username = 'Anonymous') {
  return `Hi ${username}!`;
}

greeting(); // Hi Anonymous!
```

Now if we do not pass any value to parameter `username`, instead of `undefined` JavaScript will use `'Anonymous'` value.

---

## Let's build custom Default parameters 💪

We will need 2 things:
 I. A parameters list with their values
II. A value type checker

### I. A parameter list with their values 📋

JavaScript function provides a local variable named `arguments` object that holds all the argument values.

```javascript
function greeting() {
  console.log(arguments);     // { 0: 'Bruce' }
  console.log(arguments[0]);  // 'Bruce'
}

greeting('Bruce');
```

`arguments` is an Array-like object. It holds all the argument values the function was called with, starting from index 0.
In our `greeting` function, since we are invoking it with argument `'Bruce'`, `arguments` object will hold it at 0th index.

### II. A value type checker 🕵️

JavaScript provides a unary operator named `typeof` that evaluates operand's type and returns a string value.

```javascript
function greeting() {
  console.log(arguments);            // { 0: 'Bruce' }
  console.log(typeof arguments[0]);  // 'string'
}

greeting('Bruce');
```

👩‍🏫 __Question Time:__ What will be the type if we do not pass any value?

```javascript
function greeting() {
  console.log(arguments);            // { }
  console.log(typeof arguments[0]);  // 'undefined'
}

greeting();
```

__Answer:__ It will return `'undefined'`.

__Reason:__ Since we are not passing any argument value while invoking `greeting` function, `arguments` will be an empty object and JavaScript will return `'undefined'` value for index 0.

---

## Let's combine what we learned so far and start building custom Default parameters.

```javascript
function greeting(username) {
  username = typeof arguments[0] !== 'undefined' ? arguments[0] : 'Anonymous';

  return `Hi ${username}!`;
}

greeting(); // Hi Anonymous!
```

In our `greeting` function, we access the first parameter's value with `argument[0]` and check its type using `typeof` operator.
If it does not evaluate to `'undefined'` that means an argument was passed at index 0 while invoking `greeting` function and we can use that value for `username`, else use `'Anonymous'` as a default value.

---

## Testing our function with different inputs

```javascript
function greeting(username) {
  username = typeof arguments[0] !== 'undefined' ? arguments[0] : 'Anonymous';

  return `Hi ${username}!`;
}

greeting('Bruce');      // Hi Bruce!
greeting(undefined);    // Hi Anonymous!
greeting('undefined');  // Hi undefined! (Gotcha! We are passing undefined 
                        // wrapped up in quotes as a string)
```

---

Hopefully this post was able to give you clear context on what goes behind JavaScript's Default Parameters. ❤️❤️

Follow me to get notified for next __"Behind the Abstraction"__ post coming next week!

> Cover image inspired by Wes Bos's "JavaScript functions visualized"