Destructuring in JavaScript
What is Destructuring in JavaScript?
Destructuring assignment is a special syntax in JavaScript (introduced in ES6) that allows you to “unpack” values from arrays, or properties from objects, into distinct variables. It provides a cleaner, more concise way to extract data, making your code shorter and more readable. Instead of accessing elements one by one using dot notation or bracket notation, you can get the data you need in a single, clear line.
Object Destructuring
Here is a simple example of object destructuring in JavaScript:
// The source object
const user = {
firstName: "John",
lastName: "Doe",
age: 30
};// Without destructuring
const firstNameOld = user.firstName;
const lastNameOld = user.lastName;
console.log(firstNameOld, lastNameOld); // John Doe// With destructuring
const { firstName, lastName } = user;// The variables 'firstName' and 'lastName' are now created
// and hold the corresponding values from the 'user' object.
console.log(firstName, lastName);
// The output will be:
// John Doe
Array Destructuring
Destructuring works on arrays as well. With arrays, the values are assigned based on their position or index.
// The source array
const colors = ["Red", "Green", "Blue"];// With destructuring
const [firstColor, secondColor] = colors;// The variables 'firstColor' and 'secondColor' now hold the values.
console.log(firstColor); // Red
console.log(secondColor); // Green
How do I use more advanced destructuring techniques?
Destructuring is very flexible. You can rename variables, assign default values for properties that might not exist, and even destructure nested objects and arrays.
Using Aliases to Rename Variables
Sometimes you want to assign a destructured property to a variable with a different name. You can do this using an alias.
const person = {
name: "Jane Doe",
country: "Canada"
};// Destructure 'name' but assign it to a new variable called 'fullName'
const { name: fullName, country } = person;console.log(fullName); // Jane Doe
console.log(country); // Canada
// console.log(name); // This would cause an error, as 'name' was not defined.
Break into the Code:
This code shows how to rename a variable during destructuring.
- Line 1: Define an object named
personwith two properties,nameandcountry. - Line 6: Destructure the
personobject. name: fullName: This looks for the propertynamein thepersonobject and creates a new constant namedfullNamewith its value.country: This looks for the propertycountryand creates a constant with the same name.- Line 8: The
console.logmethod prints the value offullName, which is "Jane Doe".
Using Default Values
If you try to destructure a property that doesn’t exist on the object, you’ll get undefined. You can provide a default value to prevent this.
const settings = {
theme: "dark",
fontSize: 14
};// Destructure, providing a default value for 'language'
const { theme, language = "en" } = settings;console.log(theme); // dark
console.log(language); // en
Break into the Code:
This code demonstrates providing a fallback value.
- Line 1: Define a
settingsobject that is missing alanguageproperty. - Line 6: Destructure the
settingsobject. theme: This creates a constantthemewith the value "dark".language = "en": This looks for alanguageproperty. Since it doesn't find one, it creates the constantlanguageand assigns it the default value of "en".- Line 9: The
console.logmethod prints "en", the default value we provided.
Can you give me an example of using destructuring in real-world applications?
Absolutely. Destructuring is not just a syntactic sugar; it has become a standard practice in modern JavaScript development for writing cleaner and more maintainable code.
Get Md Shoriful Islam Ashiq’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some common scenarios where destructuring is used:
1. Handling Function Parameters
Functions that take an object with multiple options are much cleaner with destructuring. You can unpack the properties you need right in the function’s signature.
// Without destructuring
function displayUser(user) {
console.log(`Name: ${user.name}, Age: ${user.age}`);
}// With destructuring
function displayUserDestructured({ name, age, profession = "Developer" }) {
console.log(`Name: ${name}, Age: ${age}, Profession: ${profession}`);
}const userProfile = { name: "Alex", age: 25 };
displayUserDestructured(userProfile); // Name: Alex, Age: 25, Profession: Developer
2. Working with API Responses
When you fetch data from an API, you often get back a large JSON object with more information than you need. Destructuring is perfect for picking out only the data you care about.
// A mock API response
const apiResponse = {
data: {
user: {
id: 123,
username: "coder1",
email: "coder1@example.com"
},
posts: [
{ id: 1, title: "First Post" },
{ id: 2, title: "Second Post" }
]
},
status: 200
};// Extract just the username and the first post's title
const { username } = apiResponse.data.user;
const { title: firstPostTitle } = apiResponse.data.posts[0];console.log(username); // coder1
console.log(firstPostTitle); // First Post
3. Swapping Variables
Array destructuring provides an incredibly clean, one-line way to swap the values of two variables without needing a temporary third variable.
let a = 1;
let b = 2;// The old way
let temp = a;
a = b;
b = temp;
// console.log(a, b); // 2 1// Reset values
a = 1;
b = 2;// The new, easy way with destructuring
[a, b] = [b, a];
console.log(a, b); // 2 1
I hope this article helps you understand how powerful and convenient destructuring is in JavaScript.
You can learn more about destructuring from these sources:









