Search code examples
javascriptecmascript-6destructuring

Confused about de-structuring function parameters


In the following example why does the whois() function have access to displayName2 and name1?

function whois({displayName: displayName2, fullName: {firstName: name1}}){
  console.log(`${displayName2} is ${name1}`)
}

let user = {
  displayName: "jdoe",
  fullName: {
      firstName: "John",
      lastName: "Doe"
  }
}
whois(user) // "jdoe is John"

To the untrained eye it looks like it should have access to displayName and fullName.firstName. The destructuring looks like JSON in reverse.

What's happening under the hood?


Solution

  • displayName and firstName were assigned new names - displayName2 and firstName1 receptively, and to access the values, you need to use the alias.

    Since only the aliases are defined as variables, trying to access the values using the old names, will throw a "variable is not defined" error.

    const destructure1 = ({ a: aa }) => console.log(aa);
    destructure1({ a: 5 }); // gets the value
    
    const destructure2 = ({ a: aa }) => console.log(a);
    destructure2({ a: 5 }); // throw an error because a is not defined

    In addition, when using destructuring with computed property names, you must assign it to a new variable name:

    const prop = 'a';
    
    const destructure1 = ({ [prop]: aa }) => console.log(aa);
    destructure1({ a: 5 }); // gets the value