Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Created April 28, 2020 19:18
Show Gist options
  • Save sandrabosk/5417e05fcc689187681b6213b9a0dca6 to your computer and use it in GitHub Desktop.
Save sandrabosk/5417e05fcc689187681b6213b9a0dca6 to your computer and use it in GitHub Desktop.
// Since the same variable names are used throughout the document (since we work on one object),
// you will have to comment out previous when demo the next.
// ************************************************
// ****************** Objects *********************
// ************************************************
let person1 = {
name: 'Ironhacker',
age: 25,
favoriteMusic: 'Metal'
};
// ES5:
let name = person1.name;
let age = person1.age;
let favoriteMusic = person1.favoriteMusic;
// ES6 way (using destructuring)
let { name, age, favoriteMusic } = person1;
console.log(`Hello, ${name}.`);
console.log(`You are ${age} years old.`);
console.log(`Your favorite music is ${favoriteMusic}.`);
// Default values
let { name, age, favoriteMusic, country = 'Spain' } = person1;
// Different variable names
const { name: fullName, age, favoriteMusic } = person1;
console.log(`Hello, ${fullName}.`); // => Hello, Ironhacker.
// Nested objects and destructuring
const person2 = {
name: 'Ironhacker',
age: 25,
favoriteMusic: 'Metal',
address: {
street: 'Super Cool St',
number: 123,
city: 'Miami'
}
};
let {
name,
age,
favoriteMusic,
address: { street, number, city }
} = person2;
console.log(`${name} lives in ${number} ${street}, city of ${city}.`);
// ==> Ironhacker lives in 123 Super Cool St, city of Miami.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment