ES6 - Use Destructuring Assignment to Pass an Object as a Function's Parameters

What is your full current code?

The tests use your function to see if it works correctly. There is no ‘somehow’ that a function finds an object - the function is called with an appropriate object as the argument.

Here is a code example with one more step.

const userInformation = {
  name: "Jim",
  age: 23,
  email: "Jim@example.com",
};

// 1. Using dot notation
function logPropertiesOnObject1(user) {
  console.log(user.name);
  console.log(user.age);
  console.log(user.email);
}

logPropertiesOnObject1(userInformation);

// 2. Using destructuring inside the function body
function logPropertiesOnObject2(user) {
  const { name, age, email } = user;
  console.log(name);
  console.log(age);
  console.log(email);
}

logPropertiesOnObject2(userInformation);

// 3. Using destructuring in the function parameter
function logPropertiesOnObject3({ name, age, email }) {
  console.log(name);
  console.log(age);
  console.log(email);
}

logPropertiesOnObject3(userInformation);

2 and 3 are very similar, in 3 we just do the destructuring directly in the parameter.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.