JavaScript Named Parameters

daleljefferson

Dale L. Jefferson

Posted on May 30, 2019

JavaScript Named Parameters

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();
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
daleljefferson
Dale L. Jefferson

Posted on May 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About