DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Destructuring assignment

Let´s talk about destructuring.

We are going to start with a simple desctruturing example.

let a,b;
[a,b] = [10, 20];

console.log(a)
// Expected output: 10
console.log(b)
// Expected output: 20
Enter fullscreen mode Exit fullscreen mode

Here we will see how defining "a" and "b" then we are assigned a value to it.

Array Destructuring

Basic variable assingnment
We are assigning a variable and then destructuring it, in order to call each part to get the specific value.

const foo = ["one", "two", "three"];

const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
Enter fullscreen mode Exit fullscreen mode

Parsing an array returned from a function

We will see how to pass a function into a destructuring variable.

function uno(){
  return [1, 2];
}

const [a,b] = uno();
console.log(a); // 1
console.log(b); // 2
Enter fullscreen mode Exit fullscreen mode

We can also ignore return values from a function

function uno(){
  return [1, 2, 3];
}

const [a, ,b] = uno();
console.log(a); // 1
console.log(b); // 3
Enter fullscreen mode Exit fullscreen mode

Object desctructuring

const user = {
  id: 42,
  isVerified: true,
};

const {id, isVerified} = user;

console.log(id); // 42
console.log(isVerified); // true
Enter fullscreen mode Exit fullscreen mode

Assigning to new variable names

const o = {p: 42, q: true};
const {p: foo, q: bar} = o;

console.log(foo); // 42
console.log(bar); // true
Enter fullscreen mode Exit fullscreen mode

Unpacking properties from objects passed as a function parameter
We will see how to unpackage properties from objects when we passed it to a function which it will return an specific thing from the object

const user = {
 id: 42,
 displayName: "jdoe",
 fullName: {
  firstName: "jane",
  lastName: "Doe"
 },
};

function userId({id}){
  return id;
}

console.log(userId(user)); // 42
Enter fullscreen mode Exit fullscreen mode

We have created a function that will return the id, so we will get the id as a parameter on the function and when we are calling the function we will pass the object "user".

If you want more examples about it you can checkout the mdn documentation

Thank you so much for reading. I hope someone found it helpful.

If you want to reach to me you can contact me through my email "lautaro.suarez.dev@gmail.com"

Lautaro.

Top comments (0)