Open In App

Parameter Destructuring

Last Updated : 12 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required. 

When only certain properties of an object or specific indexed array elements are to be used or considered within a function, it can be achieved using the concept of Parameter Destructuring. Properties of objects or specified indexed elements of an array are passed into function parameters and thus can be unpacked into distinct variables which can then be used within the function body itself. 

The properties to be accessed can be assigned a different name using an alias and can also be given default values. In case an object property or a certain array element is not present in the argument passed.

Let’s understand the concept of Parameter Destructuring using an array or an object with the help of the following examples.

1.  Destructuring Array passed as a function parameter

In the following example we will firstly create an array consisting of several elements and further will de-structured or unpack array elements into the function’s or method’s body and further will use that to print the values after calling that function later.

Javascript




// employee details in the form of an array...
let employee_details = ["Rohit", 1211, "Software Engineer"];
 
// Function made to retrieve the employee's data
// by using Parameter Destructuring...
let getDetails = ([name_of_an_employee, employee_id, employee_designation]) => {
  console.log(
    `Employee's name : ${name_of_an_employee} , Employee's ID: ${employee_id}, Employee's Designation: ${employee_designation}`
  );
};
 
getDetails(employee_details);
 
// This code is contributed by Aman Singla...


 Output:

Employee's name : Rohit , Employee's ID: 1211, Employee's Designation: Software Engineer

Note: While implementing Parameter Destructuring in which an array is passed in as function’s or method’s parameter, we may also skip one or more values of the passed in array while outputting the result over the browser’s console. Let us analyze this illustrated fact using an example mentioned below.

Javascript




<script>
 
    // Function to get Employee details
    // an array containing the employee
    // details is passed as a function
    // parameter
 
    // emp details array
    const emp = ['Rohit', 1211, 'Software Engineer'];
 
    // Skipping the employee name i.e.
    // emp[0] from the array passed
    function getDetails([ , id, designation]){
        console.log(`Employee ID: ${id}, Designation: ${designation}`);
     }
 
     getDetails(emp);
 </script>


Output:

Employee ID: 1211, Designation: Software Engineer

Default values:  Parameter can be assigned with certain default values if any certain value is not present in the array passed to the function. It may be understood in this way also that, if any value which may be or may not be present in the passed array inside the function then that could be added or replaced (in case of previous default value is present).

In the following example, ‘companyName’ variable is used as a default parameter since no corresponding value is present in the emp array

Javascript




<script>
    const emp = ['Rohit', 1211, 'Software Engineer'];
 
    // companyName is assigned a default value
    function getDetails([, id, designation,
                companyName = 'ABCTech']) {
 
        console.log(`Employee ID: ${id},
            Designation: ${designation},
            Company: ${companyName}`
        );
    }
    getDetails(emp);
</script>


Output:

Employee ID: 1211, Designation: Software Engineer, Company: ABCTech

2.  Destructuring an object passed as a function parameter: Now, using the same example as above, we’ll access only the required properties of an employee object (emp) passed as an argument to the getDetails function.

Javascript




<script>
    const emp = {
        name: 'Rohit',
        id: 1211,
        designation: 'Software Engineer'
    };
 
    // Using aliases to access the emp properties
    // skipping the 'name' property
    function getDetails({ id: empID, designation: desg }) {
        console.log(`Employee ID: ${empID}, Designation: ${desg}`);
    }
    getDetails(emp);
</script>


Output:

Employee ID: 1211, Designation: Software Engineer

In the following example, a default value is assigned to the companyName property, as it is undefined in the emp object

Javascript




<script>
    const emp = {
        name: 'Rohit',
        id: 1211,
        designation: 'Software Engineer'
    };
 
    function getDetails({ id: empID, companyName = 'ABCTech' }) {
        console.log(
            `Employee ID: ${empID}, Company: ${companyName}`);
    }
 
    getDetails(emp);
</script>


Output:

Employee ID: 1211, Company: ABCTech

Destructuring Nested Objects: Nested objects can also be de-structured within a function parameter. The following example shows the address.pincode property of the nested object address being unpacked into a variable pincode.

Javascript




<script>
    const emp = {
        name: 'Rohit',
        id: 1211,
        designation: 'Software Engineer',
        address: {
            city: 'Bangalore',
            pincode: '560004'
        }
    };
 
    // Nested object address is destructured
    // to access address.pincode
    function getDetails({ name: empName,
        id: empID, address: { pincode } }) {
 
        console.log(
            `Employee Name: ${empName},
            ID: ${empID},
            Address -> Pincode: ${pincode}`
        );
    }
     
    getDetails(emp);
</script>


Output:

Employee Name: Rohit, ID: 1211, Address -> Pincode: 560004

Destructuring Function’s return value: When any function or any method returns a specific object and we are very interested in outputting the specific property value from the returned object, then also we will use the concept of Destructuring. The following example will help us to understand the concept in much efficient manner.

Javascript




let getUsersDetails = () => {
  return {
    name: "ABCD",
    address: "XYZ City",
    age: 55,
  };
};
 
let { name, age } = getUsersDetails();
 
console.log(name, age);
 
// This code is contributed by Aman Singla...


Output:

ABCD 55


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads