Coding Triumph

Helpful code snippets & tutorials

How to destructure an object as function parameters in ES6 JavaScript

The Destructuring assignment is a new JavaScript feature added in ECMAScript 2015. It allows the extraction of values from arrays and objects into separate variables. In this post, I’ll show you how you can use this feature to extract object values into function parameters.

1. The old way:

To understand the benefits of restructuring objects into function parameters, let’s see the old way of doing things:

const cat = {
  name: 'Kitty',
  age: 3
};

function getInfo(cat) {
  // use the dot notation to access object properties
  const name = cat.name;
  const age = cat.age;

  console.log('Name:', name);
  console.log('Age:', age);
}

getInfo(cat)

// Name: Kitty
// Age: 3

Passing an object as a parameter to a function can be a little bit cumbersome if we’re only interested in its properties and not the object itself, because, in this situation, the object is redundant. This is where object destructuring comes in handy.

2. Using object restructuring:

This is the same example as above but it’s now cleaner with less code:

const cat = {
  name: 'Kitty',
  age: 3
};

function getInfo({name, age}) {
  console.log('Name:', name);
  console.log('Age:', age);
}

getInfo(cat)

// Name: Kitty
// Age: 3

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments