Working with default function parameters in JavaScript

Written by
Published on
Modified on

Default function parameters are a great addition to the JavaScript specification as of ES2015 that allows us to give a default starting value to named parameters in a function.

By default, parameters are set as 'undefined' if they are not specified.

function sum(a, b){
    let sum = a + b;

sum(1, 2); // 3
sum(1); // 'Nan'

The second function call above is equivalent to the following:

sum = 1 + 'undefined';

Typically some type of valiation code would need to be added to the function in order to avoid these edge cases.

function sum(a, b){
    let sum = 0;
    if (typeof a !== 'undefined' && typeof b !== 'undefined')
        sum = a + b;

This works, but can get tedious if having to validate multiple functions, or multiple lines of code even. The ES2015 specification in JavaScript allows us to specify a default value directly in the parameter list.

function sum(a = 0, b = 0)
    let sum = a + b;

sum();    // 0
sum(1);   // 1
sum(1, 2);    // 3

Passing 'undefined' vs passing null

If you were to pass a value of 'undefined' to the function call, the deault parameter value would override it.

function log(val = 'n/a')

log();            // 'n/a'
log(undefined);   // 'n/a'
log(null);        // null

Notice that passing null to the function will not trigger the defult to be set.

Earlier parameters can be used after

A potentially useful feature in default  parameters, is the ability to use paramters early in the list, as default values after. The following example will paint a clearer picture of that.

function sendEmail(name, greeting = 'Hey' + name){

sendEmail('Walt');                      // 'Hey Walt'
sendEmail('Walt', 'Greetings friend');  // 'Greetings friend'

Including default parameters in your function declarations is one of the quickest and simplest ways to improve your data validation model so that you can spend more time coding out logic and less time checking for data type.

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.


No messages posted yet

Developer Poll 🐱‍💻


Add a comment

Send me your weekly newsletter filled with awesome ideas