Hi there,
Are you having issues with understanding destructuring as a JavaScript developer, don't worry, you are just a minute and 55 seconds away from understanding it totally.
It is a way to extract values from arrays or objects and assign them to variables. It can be used in variable declarations, function parameter lists, and the left-hand side of assignments.
For example, you can use destructuring to extract values from an array and assign them to variables:
const places = ["Asaba", "Lagos", "Abuja"];
const [firstPlace, secondPlace, thirdPlace] = places;
console.log(firstPlace); // "Asaba"
console.log(secondPlace); // "Lagos"
console.log(thirdPlace); // "Abuja"
You can also use destructuring to extract values from an object and assign them to variables:
const person = { name: "John Doe", age: 30, gender: "male" };
const { name, age, gender } = person;
console.log(name); // "John Doe"
console.log(age); // 30
console.log(gender); // "male"
Looking at the example above, you can also assign variables to the different variable names.
const { name: fullName, age } = person;
console.log(fullName); // "John Doe"
console.log(age); // 30
You can also use destructuring in function parameters, to extract values from an object or array passed as an argument:
function printPerson({ name, age, gender }) {
console.log(name);
console.log(age);
console.log(gender);
}
printPerson(person);
In short, destructuring allows you to easily extract values from arrays and objects and assign them to variables, making your code more readable and easier to work with.
Thank you for reading, you can follow us for more demystification of concepts