Destructuring

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Destructuring

If you want to get a value from an object, you need declare the variable and assign the value to it.

// Getting values from objects
const person = {
  firstName: 'Zell',
  lastName: 'Liew'
}

const firstName = person.firstName
const lastName = person.lastName

In 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) // Zell
console.log(lastName) // Liew

You 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] = numbers

The 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) // 22
console.log(secondNumber) // 99

If there are not enough items in the array, the destructured variable will remain undefined.

const numbers = [22]
const [firstNumber, secondNumber] = numbers

console.log(secondNumber) // undefined

Destructuring 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 } = person

Here, JavaScript assigns person.firstName to the firstName variable and person.lastName to the lastName variable.

console.log(firstName) // Zell
console.log(lastName) // Liew

If you try to destructure a non-existent property, you’ll get undefined.

const course = { name: 'Learn JavaScript' }
const { description } = course

console.log(description) // undefined

Destructuring 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 declared

You can change the name of your destructured variable with colon (:).

const { name: courseName } = course
console.log(courseName) // Learn JavaScript

Destructuring function arguments

You can also destructure function arguments if the argument is an array or an object.

const scores = [100, 99, 98]
const 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 array
const emojis = ['🤢']
const [firstEmoji, secondEmoji = '😎'] = emojis

console.log(secondEmoji) // 😎
// Fallback value for destructured object
const 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:

  1. Get the first two items in posts with destructuring.
  2. Get the id and title of the first post with destructuring.
  3. Rename the title of the first post to content while you destructure.
  4. 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 💩'
}, {
  id: 801,
  title: 'Pooing is a natural thing.'
}, {
  id: 802,
  title: 'Poo jokes are getting irritating'
}]

Answers

  • Get the first two items in posts with destructuring.
const [post1, post2] = posts
  • Get the id and title of the first post with destructuring.
const [post1] = posts
const {title, id} = post1
console.log(title) // This is 💩
console.log(id) // 800
  • Rename title of the first post to content while you destructure.
const [post1] = posts
const {title: content} = post1
console.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] = posts
const {
  description = 'Nothing is better than leaving the description empty'
} = post1
console.log(description) // 'Nothing is better than leaving the description empty'