Understanding Default Parameters in JavaScript

In ECMAScript 2015, default function parameters were introduced to the JavaScript language. These allow developers to initialize a function with default values if the arguments are not supplied to the function call. Initializing function parameters in this way will make your functions easier to read and less error-prone, and will provide default behavior for your functions. This will help you avoid errors that stem from passing in undefined arguments and destructuring objects that don’t exist.

In this article, you will review the difference between parameters and arguments, learn how to use default parameters in functions, see alternate ways to support default parameters, and learn what types of values and expressions can be used as default parameters. You will also run through examples that demonstrate how default parameters work in JavaScript.

Something that’s not really underlined in the article is the fact that these default function parameters are evaluated at call time. Take this snippet for example:

function test(when = new Date()) {
  console.log(when);
}

In case when is omitted (and thus has the value of undefined), its value will be set to the date it was at the moment the function was called.

💡 This way you can also build required parameters into JavaScript:

Understanding Default Parameters in JavaScript →

🧞‍♂️ The way default function parameters in JavaScript work is something that’s actually on my PHP wishlist: at call time evaluation of a default argument value. That way we could default a function argument $when to be new \DateTime('now', new \DateTimeZone('UTC')) in case it’s omitted.

// As you have to do it now
function isCardValidAtTime(Card $card, \DateTime $when = null) {
  $when = $when ?? new \DateTime('now', new \DateTimeZone('UTC'));
  // (function logic)
}

// As I would like to do it in
function isCardValidAtTime(Card $card, \DateTime $when = new \DateTime('now', new \DateTimeZone('UTC'))) {
  // (function logic)
}

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.