DEV Community

loading...

Destructuring `array`

Mehul Lakhanpal
Full stack Developer | Micro-blogging on Web Development at codedrops.tech | Creator of File Ops, Note Box, GitHub Marker
Originally published at codedrops.tech ・1 min read
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

Discussion (2)

Collapse
pris_stratton profile image
pris stratton

Destructuring is a very cool technique 👌

Collapse
318097 profile image
Mehul Lakhanpal Author

Agree