Mastering Destructuring in Javascript

Mastering Destructuring in Javascript

Q: What do you call an object that's been destructured?

A: A bunch of properties. 🤣.

Destructuring is a powerful ES6 feature that simplifies code and enhances readability by unpacking values from arrays or objects into distinct variables. Let's explore how it works and its applications for arrays and objects.

Destructuring Arrays

Destructuring arrays involves using square brackets ([]) in the assignment, allowing you to assign specific array elements to variables.

const colors = ["Red", "Blue", "Brown"];
const [first, second, third] = colors;

console.log(first);  // Red
console.log(second); // Blue
console.log(third);  // Brown

Order is crucial in array restructuring, the variables' order reflects the array's element order. You can skip elements by leaving empty spaces.

const colors = ["Red", "Blue", "Brown"];
const [ , ,third] = colors;
console.log(third);  // Brown

Swapping Elements in an Array

Destructuring can be used to swap the positions of elements in an array and put them in a new array.

const flowers = ["Rose", "Dandellions", "Lily"];
let [one, two, three] = flowers;
[one, two, three] = [three, one, two];

const newFlowers = [one, two, three];
console.log(newFlowers);

Note: Swapping values does not in any way alter the original array, Destructuring also does not in any way alter or modify the original array.

Destructuring Arrays in Functions

You can also destructure arrays passed into a function or destructure an array when you return it from a function. In the example below the numbers function takes an array of numbers, multiplies them by 2, and returns the new values in an array.

const numbers = ([one, two, three, four, five]) => {
    one *= 2;
    two *= 2;
    three *= 2;
    four *= 2;
    five *= 2;
    return [one, two, three, four, five];
};

const [first, second, third, fourth, fifth] = numbers([1, 2, 3, 4, 5]);
console.log(first, second, third, fourth, fifth);

Destructuring Nested Arrays

Nested arrays can be destructured by nesting the destructuring assignment when destructuring it.

const colors = ["Red", "Yellow", "Brown", ["Blue", "SkyBlue", "Cyan"], "Black"];
const [first, second, third, [fourth, fifth, sixth], seventh] = colors;
console.log(first, second, third, fourth, fifth, sixth, seventh);

Don’t mind my variable name, choosing variable names is not my strength🥲.

Default Values in Array Destructuring

You can set default values to avoid undefined values when destructuring arrays of varying lengths. Do this by assigning the default value for each variable in the destructuring assignment.

const flowers = ["rose", "sunflower", "lily"];
const [first = "flower", second = "flower", third = "flower", fourth = "flower"] = flowers;
console.log(first, second, third, fourth);

Destructuring Objects

Similar to arrays, objects can undergo destructuring through the {} destructuring assignment. Unlike arrays, the order of properties in an object doesn't impact the process. Consequently, if there's no intention to destructure a specific property, there's no need to allocate extra space for it, a departure from the approach employed when destructuring arrays. It's important to emphasize that when destructuring an object, the variable names must precisely match the property names in the object.

const myBio = {
  name: "John Doe",
  age: 36,
  gender: "Male",
};

const { name, age, gender } = myBio;
console.log(name, age, gender);

Variable Renaming in Object Destructuring

When destructuring an object, you can set a different variable name instead of using the same name as the property in the variable.

const myBio = {
  name: "John Doe",
  age: 36,
  gender: "Male",
};

const { name: fullname, age: myAge, gender: myGender } = myBio;
console.log(fullname, myAge, myGender);

Default Values in Object Destructuring

You can specify default values to handle missing properties during object destructuring. In a probable situation where a property is not available in the Object, the default value would be printed.

const myBio = {
  name: "John Doe",
  age: 36,
  gender: "Male",
};

const { name = "", age = "", gender = "", country = "" } = myBio;
console.log(name, age, gender, country);

Note that, the default values don’t always have to be an empty string, you can set a number, an array, or an object also.

Mutating Variables while Destructuring Objects:

You can reassign object properties to previously declared variables while destructuring. To do that you would have to wrap the whole statement in parentheses so that it doesn’t throw an error in Javascript.

let name = "John Doe";
let gender = "Male";
const obj = { name: "Jane Doe", gender: "Female" };
({ name, gender } = obj);
console.log(name, gender);

Destructuring Nested Objects:

Destructuring nested objects follows a similar syntax to that of arrays but uses colons and nested curly braces.

const person = {
  name: "John Doe",
  age: 30,
  school: {
    elementary: "WANPS",
    college: "UNN",
  },
};

const { name, age, school: { elementary, college } } = person;
console.log(name, age, elementary, college);

Destructuring Objects in Functions:

When passing an object to a function, you can destructure it directly in the parameter list.

const foodDelivery = ({ food, time, address }) => `${food} will be delivered to ${address}, at ${time}`;
foodDelivery({ food: "Pizza", time: "13:00", address: "Hogwarts Academy" });

Conclusion

Destructuring in JavaScript, a feature introduced in ES6, serves as a powerful tool for simplifying and improving code clarity. Whether unraveling arrays or extracting values from objects, destructuring provides an elegant and concise syntax, making code more readable and maintainable. Its versatility extends to handling nested structures, setting default values, and even mutating variables during the deconstruction process, showcasing its advantages across various scenarios. As a fundamental skill for JavaScript developers, mastering destructuring enhances coding efficiency and contributes to the creation of cleaner, more expressive code.