Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Created June 4, 2017 09:11
Show Gist options
  • Save brauliodiez/05fa34677446c42df9f69e40ae8f0068 to your computer and use it in GitHub Desktop.
Save brauliodiez/05fa34677446c42df9f69e40ae8f0068 to your computer and use it in GitHub Desktop.
Simple Destructuring sample

Destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

steps

Let's create a function that will concat a given client name and lastname.

const client = {
  id: 2324,
  name : 'John',
  lastname : 'Doe',
  city: 'London',
};

function buildFullname(client) {
  return `${client.name} ${client.lastname}`;
}

console.log(buildFullname(client));

We can use destructuring and unpack just name and lastname and use it directly in our function, without having to refer to the client instance.

const client = {
  id: 2324,
  name : 'John',
  lastname : 'Doe',
  city: 'London',
};

- function buildFullname(client) {
+ function buildFullname({name, lastname})
-  return `${client.name} ${client.lastname}`;
+ return  `${name} ${lastname}`;
}

console.log(buildFullname(client));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment