Javascript Destructuring | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Javascript Destructuring

var obj = {id: 42, name: "Jack"}; let {id = 10, age = 20} = obj; console.log(id); // 42 console.log(age); // 20 why does the id output is 42 and not 10.Doesn't the let makes the second id value assigned override the old value which is 42 and thus takes a new value which is 10?

24th May 2020, 3:46 PM
Mas Hairul Adham
Mas Hairul Adham  - avatar
4 Answers
+ 5
It's default parameter, used when the key is not contained in the destructured object. For age, because the key isn't contained in obj, so the default parameter effect. For id, because the key already exists, the default parameter is disregarded and the value in obj is extracted.
24th May 2020, 4:20 PM
Gordon
Gordon - avatar
+ 11
• How to Use Object Destructuring in JavaScript — https://dmitripavlutin.com/javascript-object-destructuring/
24th May 2020, 4:51 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
You can set a default value if the property doesn’t exist in the destructured object.
24th May 2020, 4:38 PM
Calviղ
Calviղ - avatar
0
the equal sign changes the values first id = 42, then the id = 10 and lastly {id = 10} = {id = 42} therefor the last value of the id is 42; In short the last value to be passed is true😍😍
23rd Sep 2020, 10:46 AM
Jack Murimi Kavita
Jack Murimi Kavita - avatar