Craft By Zen

šŸ“– 1 min read

šŸ”– essay   blog   post   programming   learning

Object Deconstruction in Javascript

Writing cleaner Javascript

The Javascript ES2015 spec introduces object destructing. Object destructing used to pass a single object parameter instead of long argument lists to functions. Take the following code example.

Bad Code:

function enableListFilter(option, filterName, filterIndex, activeAccessTypeIndex) {
  // Do Something
}

enableListFilter(option, filterName, filterIndex, activeAccessTypeIndex);

The function requires the developer to know the order of the parameters passed into the function. When this is one argument, thatā€™s easy. When it gets to 2 or more arguments, this can get difficult since that stretches a developerā€™s working memory a la ā€œyet another thing to rememberā€. Hereā€™s an alternative.

Better Code:

function enableListFilter({ option, filterName, filterIndex, activeAccessTypeIndex }) {
  // Do Something
}

enableListFilter({
  option: option,
  filterName: filterName,
  filterIndex: filterIndex,
  activeAccessTypeIndex: activeAccessTypeIndex
});

If you want to reduce the number of lines, you can use the object parameter shorthand. Note: A caveat of this approach your argument names must be the same name. In most cases, an explicit approach of writing out object keys is better.

enableListFilter({ option, filterName, filterIndex, activeAccessTypeIndex });

Written by Jeremy Wong and published on .