Skip to content

Instantly share code, notes, and snippets.

@tararoutray
Last active August 31, 2021 17:12
Show Gist options
  • Save tararoutray/9a5c9e459d9301ff78299591fab33e62 to your computer and use it in GitHub Desktop.
Save tararoutray/9a5c9e459d9301ff78299591fab33e62 to your computer and use it in GitHub Desktop.
// Array destructuring
// Initialize an array with sample data
const userDetails = ['Luis James', '24', '[email protected]'];
// Destructure the above array - extract the array elements to variables
const [username, age, email] = userDetails;
console.log(username); // This will print: Luis James
console.log(age); // This will print: 24
console.log(email); // This will print: [email protected]
// A variable can be assigned a default value, in the case that the value unpacked from the array is undefined.
let username, age;
[username = '', age = 25] = ['Luis James'];
console.log(username); // This will print: Luis James
console.log(age); // This will print: 25
// Parsing an array returned from a function
const users = () => {
return ['Jackie', 'Christopher'];
}
let userOne, userTwo;
[userOne, userTwo] = users();
console.log(userOne); // This will print: Jackie
console.log(userTwo); // This will print: Christopher
// Object destructuring
const userAccountDetails = { id: 100, emailVerified: true };
const {id, emailVerified} = userAccountDetails;
console.log(id); // This will print: 100
console.log(emailVerified); // This will print: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment