DEV Community

Cover image for Power of destructuring
Rahul Raj
Rahul Raj

Posted on

Power of destructuring

Destructuring is a blessing to JavaScript and TypeScript developers.
Destructuring works for both Object & Arrays.

Object Destructuring

Consider the below object:

const myObject = {
  userFirstName: 'Rahul',
  userLastName: 'Raj',
}
Enter fullscreen mode Exit fullscreen mode

How will you fetch the firstName and lastName in separate variables.

const userFirstName= this.myObject.userFirstName;
const userLastName= this.myObject.userLastName;
console.log(userFirstName) // Rahul
console.log(userLastName) // Raj
Enter fullscreen mode Exit fullscreen mode

OR
You can use the destructuring.

const {userFirstName, userLastName} = this.myObject;
console.log(userFirstName) // Rahul
console.log(userLastName) // Raj
Enter fullscreen mode Exit fullscreen mode

This simple 1 liner will get you your values in the keyName variable.

You don't like the lengthy variable name 🤔
Change it to your desired names by giving an alias name.

const {userFirstName: fN, userLastName: lN} = this.myObject;
console.log(fN); // Rahul
console.log(userFirstName); // Will through error
Enter fullscreen mode Exit fullscreen mode

So you have learnt almost everything about object destructuring.

Array Destructuring

Array destructuring is similar to Object destructuring but it is used when we know the number of elements or need the initial element to work with.

    const userDetails:string = "Rahul,dev.to,rahulrajrd";
    const [name, website, username, noItemCheck] = userDetails.split(",");
    console.log(name); // Rahul
    console.log(website); // dev.to
    console.log(username); // rahulrajrd
    console.log(noItemCheck) // undefined
Enter fullscreen mode Exit fullscreen mode

🟥 Important Note.

If the returned value is less than the assigned value as shown above the value will be undefined.

If you like the post follow me for more

Top comments (0)