DEV Community

Cover image for Understanding JavaScript Default Parameters - Behind the Abstraction
Dutiyesh Salunkhe
Dutiyesh Salunkhe

Posted on • Updated on

Understanding JavaScript Default Parameters - Behind the Abstraction

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.

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

greeting('Bruce'); // Hi Bruce!
Enter fullscreen mode Exit fullscreen mode

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?

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

greeting(); // Hi undefined!
Enter fullscreen mode Exit fullscreen mode

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.

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

greeting(); // Hi Anonymous!
Enter fullscreen mode Exit fullscreen mode

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.

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

greeting('Bruce');
Enter fullscreen mode Exit fullscreen mode

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.

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

greeting('Bruce');
Enter fullscreen mode Exit fullscreen mode

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

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

greeting();
Enter fullscreen mode Exit fullscreen mode

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.

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

  return `Hi ${username}!`;
}

greeting(); // Hi Anonymous!
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

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"

Oldest comments (0)