2

My code:

const users = [ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]

p = new Promise( resolve => resolve(users) )

p.then( (user) => console.log(user) )   

Return me the following logs:

[ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]

If I change it as below,

users.then( ([user]) => console.log(user) ) 

I receive the following logs:

{ id: 1, name: 'user1' }

I don't quite understand why the second one only logs the first element in the array.

2
  • users.then( ([user1, user2]) => console.log(user1, user2) ) - this logs both the users. Commented Jun 15, 2018 at 7:51
  • Because [user] used the way you have it is destructing and that says to get the first item from the array and given it a name of user. Commented Jun 15, 2018 at 7:52

2 Answers 2

4

It's a destructuring assignment

[a, b, c] = [1, 2, 3]

console.log(a)
console.log(b)
console.log(c)

but if you only destructure one, you get the first value of the array

[a] = [1, 2, 3]

console.log(a)

As for your example, destructuring can be done in many places such as function arguments

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for a simple, but very useful answer
0

Destructuring is an ES6 aka ECMA2015 features.

You can destructure Array and Objects.


Object destructuring as bellow, allow you to pick up the keys you want to get from an object using easy syntax.

const obj = {
  a: 'a',
  b: 'b',
  c: 'c',
};

// Without object destructuring
const a_ = obj.a;
const b_ = obj.b;


// With object destructuring
const {
  a,
  b,
} = obj;

console.log(a);


Array destructuring is quite the same, but instead of specifying the keys you want to get, you use the index of the data.

const arr = [
  'a',
  'b',
  'c',
];

// Without array destructuring
const a_ = arr[0];
const c_ = arr[2];

// With array destructuring
const [
  a, , c,
] = arr;

console.log(c);


You can use Array and Object destructuring anywhere; including in function parameters. It's especially good in this case because you can assign default value easily to keys, as bellow

function func({
  a,
  b,
  c = 'default',
}) {
  console.log(a, '/', b, '/', c);
}

func({
  a: 'j\'aime la france',
  b: 'vive les baguettes',
});

1 Comment

Awesomeeee I totally got it now. Thank you for giving many examples

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.