DEV Community

Cover image for Javascript Array/Object Destructuring - With Some Tricks You Probably Dont Know
Syakir
Syakir

Posted on • Originally published at devaradise.com

Javascript Array/Object Destructuring - With Some Tricks You Probably Dont Know

This post is originally posted at https://devaradise.com/js-array-object-destructuring/

Discover some tips and tricks to destructure array and object in javascript from basic to advanced use case that you probably don't know.

Destructuring is a powerful feature in JavaScript that allows you to extract values from an array or object properties into distinct variables. It provides a more readable and concise syntax for handling data structures, making your code cleaner and more maintainable.

In this article, weโ€™ll explore the basics of array and object destructuring, along with some advanced use cases.

Array Destructuring

Array destructuring allows you to unpack values from arrays into separate variables. This can simplify the process of working with arrays and make your code more readable.

Basic Array Destructuring

Hereโ€™s a simple example of array destructuring:

const fruits = ['apple', 'banana', 'cherry'];

const [first, second, third] = fruits;

console.log(first); // Outputs: apple
console.log(second); // Outputs: banana
console.log(third); // Outputs: cherry
Enter fullscreen mode Exit fullscreen mode

Skipping Items

You can skip items in an array by using commas:

const colors = ['red', 'green', 'blue', 'yellow'];

const [primary, , secondary] = colors;

console.log(primary); // Outputs: red
console.log(secondary); // Outputs: blue
Enter fullscreen mode Exit fullscreen mode

Assigning Default Value

You can assign a default value to an index, in a case when you dont know if the array have enough length. For example, when you receive the array from a backend API

const numbers = [1, 2];

const [a, b, c = 3] = numbers;

console.log(a); // Outputs: 1
console.log(b); // Outputs: 2
console.log(c); // Outputs: 3 (default value)
Enter fullscreen mode Exit fullscreen mode

Swapping Variables

Array destructuring makes it easy to swap variables without using a temporary variable:

let x = 1;
let y = 2;

[x, y] = [y, x];

console.log(x); // Outputs: 2
console.log(y); // Outputs: 1
Enter fullscreen mode Exit fullscreen mode

Destructure some items only + Rest operator

const [first, second, ...rest] = [10, 20, 30, 40, 50];

console.log(first); // Outputs: 10
console.log(second); // Outputs: 20
console.log(rest); // Outputs: [30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

Object Destructuring

Object destructuring allows you to extract properties from objects into distinct variables. It provides a concise way to access object properties.

Basic Object Destructuring

Hereโ€™s a basic example of object destructuring:

const person = {
    name: 'John',
    age: 30,
    city: 'New York'
};

const { name, age, city } = person;

console.log(name); // Outputs: John
console.log(age); // Outputs: 30
console.log(city); // Outputs: New York
Enter fullscreen mode Exit fullscreen mode

Renaming Variables

You can rename variables while destructuring by using a colon:

const user = {
    username: 'jdoe',
    email: 'jdoe@example.com'
};

const { username: userName, email: userEmail } = user;

console.log(userName); // Outputs: jdoe
console.log(userEmail); // Outputs: jdoe@example.com
Enter fullscreen mode Exit fullscreen mode

Assigning Default Value

Like Array destructuring, you can also assign the default value of property in case the object doesnโ€™t have the specified property

const options = {
    timeout: 1000
};

const { timeout, retries = 3 } = options;

console.log(timeout); // Outputs: 1000
console.log(retries); // Outputs: 3 (default value)
Enter fullscreen mode Exit fullscreen mode

Nested Destructuring

You can destructure nested objects and arrays easily:

const employee = {
    name: 'Alice',
    position: {
        title: 'Developer',
        level: 'Junior'
    },
    skills: ['JavaScript', 'React']
};

const {
    name,
    position: { title, level },
    skills: [primarySkill, secondarySkill]
} = employee;

console.log(name); // Outputs: Alice
console.log(title); // Outputs: Developer
console.log(level); // Outputs: Junior
console.log(primarySkill); // Outputs: JavaScript
console.log(secondarySkill); // Outputs: React
Enter fullscreen mode Exit fullscreen mode

Combining Array and Object Destructuring

You can combine array and object destructuring to handle complex data structures:

const data = {
    users: [
        { id: 1, name: 'John' },
        { id: 2, name: 'Jane' }
    ]
};
const {
    users: [{ name: firstName }, { name: secondName }]
} = data;

console.log(firstName); // Outputs: John
console.log(secondName); // Outputs: Jane
Enter fullscreen mode Exit fullscreen mode

Function Parameters Destructuring

Destructure arrays and objects directly in function parameters:

Array Destructuring in Function Parameters

function sum([a, b]) {
    return a + b;
}

console.log(sum([1, 2])); // Outputs: 3
Enter fullscreen mode Exit fullscreen mode

Object Destructuring in Function Parameters

function greet({ name, age }) {
    return `Hello, my name is ${name} and I am ${age} years old.`;
}

const person = { name: 'John', age: 30 };

console.log(greet(person)); // Outputs: Hello, my name is John and I am 30 years old.
Enter fullscreen mode Exit fullscreen mode

Destructuring with Promises

Handle asynchronous data with destructuring:

const fetchData = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                user: {
                    id: 1,
                    name: 'John Doe'
                },
                posts: [
                    { id: 1, title: 'Post 1' },
                    { id: 2, title: 'Post 2' }
                ]
            });
        }, 1000);
    });
};

fetchData().then(({ user, posts }) => {
    console.log(user.name); // Outputs: John Doe
    console.log(posts[0].title); // Outputs: Post 1
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Array and object destructuring in JavaScript provides a concise and readable way to extract values from arrays and objects. By leveraging destructuring, you can simplify your code, making it more maintainable and easier to understand. Whether youโ€™re dealing with simple arrays and objects or complex nested structures, destructuring offers a powerful tool for efficient data handling in JavaScript.

Do you know another trick for array/object destructuring?
Dont hesitate to share it in the comment below!

Top comments (3)

Collapse
 
oculus42 profile image
Samuel Rouse

Thanks for producing a great article!

I have an addition that may be helpful in limited scenarios.

Defaults & Variables

When creating default values, you can refer to previously declared variables, even ones inside the same destructuring.

const employee = {
    name: 'Alice',
    position: {
        title: 'Developer',
        level: 'Junior'
    },
    skills: ['JavaScript', 'React']
};

const { position: { title, level }, computedRole = `${level} ${title}` } = employee;
computedRole;
// 'Junior Developer'
Enter fullscreen mode Exit fullscreen mode

We can even run code inside defaults:

const {
  name,
  skills,
  knowsReact = skills.includes('React'),
} = employee;
knowsReact;
// true
Enter fullscreen mode Exit fullscreen mode

With array destructuring, you can only refer to variables from outside of from a previous index. These rule are a little more fluid with object destructuring, but I'm not sure of limitations.

Finally, in the rare cases you need it, you can refer to a key multiple times in desturcturing.

const {
  position: { title }, // get title
  position, // get position
} = employee;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
syakirurahman profile image
Syakir

Thank you for additional tricks. ๐Ÿ˜„ I will add this to the original post later

Collapse
 
shajim profile image
SHAJIM

useful for beginners .