logo

Unpacking fields from objects passed as a function parameter

March 31, 2021

Rather than destructuring inside the function body, we can unpack the values we want right in the parameter list.

const user = {
  id: 100674,
  firstName: "Joe",
  lastName: "Tribni",
  country: "Denmark",
};

function printUser(user) {
  const { id, firstName, lastName } = user;
  console.log(`${id} - ${firstName} ${lastName}`);
}

console.log(printUser(user)); // 100674 - Joe Tribni

We can the values right in the parameter list:

function printUserInformation({ id, firstName, lastName }) {
  console.log(`${id} - ${firstName} ${lastName}`);
}

console.log(printUserInformation(user)); // 100674 - Joe Tribni