DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Destructuring `array`

const data = { name: "Test", skills: ["javascript", "css", "react", "node"] };

// Extract 1st item
const [firstSkill] = data.skills;
console.log(firstSkill); // javascript

// Extract 3rd item (Skip 1st & 2nd)
const [, , thirdSkill] = data.skills;
console.log(thirdSkill); // react

// Nested destructuring (Direct from object)
const {
  skills: [firstSkillAgain],
} = data;
console.log(firstSkillAgain); // javascript

// Assign default value if nested array not found
const { tags: [firstTag] = ["Custom Value 1", "Custom Value 2"] } = data;
console.log(firstTag); // Custom Value 1
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Top comments (2)

Collapse
 
pris_stratton profile image
pris stratton

Destructuring is a very cool technique 👌

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Agree