Dale Jefferson

Dale L. Jefferson

TypeScript, JavaScript, React, React Native

JavaScript Named Parameters

By Dale Jefferson. Published
JavaScript, TypeScript

I find JavaScript’s lack of named parameters frustrating. In this article, I will show you how you can get the same effect and as a bonus, show you how to achieve default values.

Without Named Parameters

This is how you are likely writing functions without named parameters.

const formatDate = (day, month, year) => {
  return `${day}/${month}/${year}`;
};

// Somewhere else in your code.
formatDate(1, 2, 2018); // Good: Little-endian?
formatDate(2, 1, 2018); // Bad: Middle-endian?
formatDate(2018, 2, 1); // Bad: Big-endian?

I’ve never understood the American middle-endian date format.

With Named Parameters

In this example, I’m using Object destructuring to mimic named parameters.

const formatDate = ({day, month, year}) => {
  return `${day}/${month}/${year}`;
};

// Very readable, order you parameters anyway you like.
formatDate({day: 1, month: 2, year: 2018});
formatDate({month: 2, day: 1, year: 2018});
formatDate({year: 2018, month: 2, day: 1});

Default Values

In this example, I’m providing default values to day, month and year making them optional.

const formatDate = ({day = 0, month = 0, year = 2018} = {}) => {
  return `${day}/${month}/${year}`;
};

// Just pass the parameters you need.
formatDate({day: 1, month: 2, year: 2018});
formatDate({month: 2, year: 2018});
formatDate({year: 2018});
formatDate({});
formatDate();

Updated to allow for formatDate() thanks for the feedback.