If you want to get a value from an object, you need declare the variable and assign the value to it.
// Getting values from objectsconst person = { firstName: 'Zell', lastName: 'Liew',}
const firstName = person.firstNameconst lastName = person.lastNameIn ES6, you can destructure variables—a process to declare and assign multiple variables with one line of code.
const { firstName, lastName } = person
console.log(firstName) // Zellconsole.log(lastName) // LiewYou can destructure arrays too. Destructured arrays and objects behave differently. Let’s dive into each of them to understand their nuances.
Destructuring arrays
To destructure an array, you write the names of the variables you’d like to declare within square brackets ([]).
const numbers = [22, 99, 100]const [firstNumber, secondNumber] = numbersThe first destructured variable will always be the first item in the array, the second destructured variable will always be the second item, and so on…
console.log(firstNumber) // 22console.log(secondNumber) // 99If there are not enough items in the array, the destructured variable will remain undefined.
const numbers = [22]const [firstNumber, secondNumber] = numbers
console.log(secondNumber) // undefinedDestructuring objects
To destructure an object, you write the names of the properties you’d like to declare as variables in curly braces ({}).
const person = { firstName: 'Zell', lastName: 'Liew',}
const { firstName, lastName } = personHere, JavaScript assigns person.firstName to the firstName variable and person.lastName to the lastName variable.
console.log(firstName) // Zellconsole.log(lastName) // LiewIf you try to destructure a non-existent property, you’ll get undefined.
const course = { name: 'Learn JavaScript' }const { description } = course
console.log(description) // undefinedDestructuring with a different variable
You declare variables when you destructure. That means you cannot have two variables of the same name:
const name = 'Zell Liew'const course = { name: 'Learn JavaScript' }
const { name } = course // Uncaught SyntaxError: Identifier 'name' has already been declaredYou can change the name of your destructured variable with colon (:).
const { name: courseName } = courseconsole.log(courseName) // Learn JavaScriptDestructuring function arguments
You can also destructure function arguments if the argument is an array or an object.
const scores = [100, 99, 98]function firstThree ([first, second, third]) { return { first: first second: second third: third }}
console.log(firstThree(scores))// {// first: 100,// second: 99,// third: 98// }Default parameters when destructuring
You can provide fallback values for destructured variables with =.
// Fallback value for destructured arrayconst emojis = ['🤢']const [firstEmoji, secondEmoji = '😎'] = emojis
console.log(secondEmoji) // 😎// Fallback value for destructured objectconst course = { name: 'Learn JavaScript' }const { description = 'Best JavaScript course ever!' } = course
console.log(description) // Best JavaScript course ever!Wrapping up
Destructuring gives you a way to extract values from objects and arrays quickly.
To destructure an array, you use []. The first destructured variable is always the first item in the array, the second destructured variable is the second item in the array, and so on.
To destructure an object, you use {}. The destructured variable should be the property name of the object. You can even rename destructured variables if you wish to.
You can also provide default values to a destructured variable if it doesn’t exist.
Exercise
Perform these actions with the following set of data:
- Get the first two items in
postswith destructuring. - Get the
idandtitleof the first post with destructuring. - Rename the
titleof the first post tocontentwhile you destructure. - The first post doesn’t have a description. Create one as you destructure. Set it to
Nothing is better than leaving the description empty.
const posts = [ { id: 800, title: 'This is 💩', status: published, }, { id: 801, title: 'Pooing is a natural thing.', status: published, }, { id: 802, title: 'Poo jokes are getting irritating', status: published, },]Get the first two items in posts with destructuring.
const [post1, post2] = postsGet the id and title of the first post with destructuring.
const [post1] = postsconst { title, id } = post1console.log(title) // This is 💩console.log(id) // 800Rename title of the first post to content while you destructure.
const [post1] = postsconst { title: content } = post1console.log(content) // This is 💩The first post doesn’t have a description. Create one as you desctructure. Set it to Nothing is better than leaving the description empty.
const [post1] = postsconst { description = 'Nothing is better than leaving the description empty' } = post1console.log(description) // 'Nothing is better than leaving the description empty'Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson