JS Destructuring For Newbies by@jony1

JS Destructuring For Newbies

Object/Array destructuring is one of the new ES6 features and is very helpful. If you want to be a competent React developer - this is the topic you should not miss, since destructuring used quite heavily in React.js The main superpower of destructuring is the ability to take apart an object or an array. So we can extract just the information we need.
image
Jony Darko HackerNoon profile picture

Jony Darko

Coding is fun. Helping others to understand programming.


A few important things to consider before we begin:


I am a beginner developer and writing articles is my way of learning, this means that there might be errors. If you find any, please let me know in the comments and І will correct them :)

Some of the information like definitions or examples are taken from the internet, if you see something that belongs to you and would like credit or it to get removed - please contact me and І will be happy to do so.


Learning is fun, so let’s go!🔥


Object/Array destructuring is one of the new ES6 features and is very helpful. If you want to be a competent React developer - this is the topic you should not miss, since destructuring used quite heavily in React.js


The main superpower of destructuring is the ability to take apart an object or an array. So we can extract just the information we need.


Here we have two arrays:

const alphabet = ['A', 'B', 'C', 'D', 'E', 'F']
const numbers = ['1', '2', '3', '4', '5', '6']


Let’s say that we want to take the first two elements from our alphabet array. We could do something like this:


const a = alphabet[0]
const b = alphabet [1]
console.log(a)//A 
console.log(b)//B


First, we create const “a“ which will store the extracted information. Next, we take our array alphabet and search for the first item in it - which is at the position [0] (in JS count starts from 0) . Similarly, we then create const “b” to store the value of the second item, which can be found on position [1] .


Now let’s see how it works with destructuring:

const [a, b] = alphabet
console.log(a)//A
console.log(b)//B


Here we put the first two variables in brackets and set them equal to our array alphabet . Note that we can give them any names i.e const [z, q] = alphabet ,const [g, i] = alphabet etc. When we console.log the result, z,g will give us A and consequently q,і will produce B .

Basically, we put something we want to take apart on the right and what we want to take out on the left.


As well it works with more than just two elements:

const [a, b, k] = alphabet
console.log(a)//A
console.log(b)//B
console.log(k)//C


Let’s imagine that we would like to skip the second element.

const [a,, c] = alphabet
console.log(a)//A
console.log(c)//C

Easy! Just delete it and leave the coma , .


Let’s say, we need to leave out the second element BUT include all the rest of our array.

const [a,, c, ...rest] = alphabet
console.log(a)//A
console.log(c)//C
console.log(rest)//["D", "E", "F"]

In this case, we can use the spread operator (don’t forget to give it a name). It can be any name, here we used rest , names like Rest, Rest1 works but using only numbers as a name і.e 1, 324 will not work.


Congratulations, you got + 4 EXP

image



Now, when we mastered the basics we can do more advanced magic by combining destructuring and spread operator to combine two arrays.

const alphabet = ['A', 'B', 'C', 'D', 'E', 'F']
const numbers = ['1', '2', '3', '4', '5', '6']


To do it we first create a new array and use the spread operator to get all the elements in alphabet array and similarly …numbers, to get all the elements in the numbers array

const alphabet = ['A', 'B', 'C', 'D', 'E', 'F']
const numbers = ['1', '2', '3', '4', '5', '6']

const newArray = [...alphabet, ...numbers]
console.log(newArray) //['A', 'B', 'C', 'D', 'E', 'F', '1', '2', '3', '4', '5', '6']


Note that we can do it with concat . Concatenate - concat, means to join. So this:

const newArray = alpphabet.concat(numbers)

will produce the same result as:

const newArray = [...alphabet, ...numbers]


Considering arrays, here’s another good use of destructuring - the function that returns more than 1 parameter.


First, let’s see an example without destructuring.

function sumAndMultiply(a, b) {
return [a+b, a*b]
}

const array = sumAndMultiply(2, 3)
console.log(array)// [5, 6]

We create function sumAndMultiply , pass a and b into it. Inside we create an array that would Sum and Multiply these numbers. Lastly, we create const array that will store the result and set it equal to our function sumAndMultiply inside of which, we pass 2 and 3.


So how can destructuring be applied here?

function sumAndMultiply(a, b) {
return [a+b, a*b]
}

const [sum, multiply] = sumAndMultiply(2, 3)
console.log(sum)// 5
console.log(multiply)// 6

Basically, we say that we want to get the two elements from our function. Note that the names can be anything, і.e const [Sum, mulTiply], const [bob, apple] etc.


As you can see, using destructuring gives more control over the information that we want to extract.


Another feature that becomes available when using destructuring while working with functions is that we can set default values.

function sumAndMultiply(a, b) {
return [a+b, a*b]
}

const [sum, multiply, division = 'No division'] = sumAndMultiply(2, 3)
console.log(sum)// 5
console.log(multiply)// 6
console.log(division)// No division

Here, by default we get “No division” because our function sumAndMultiply return only two properties. If we pass another property a/b

function sumAndMultiply(a, b) {
return [a+b, a*b, a/b]
}

const [sum, multiply, division = 'No division'] = sumAndMultiply(2, 3)
console.log(sum)// 5
console.log(multiply)// 6
console.log(division)// 0.6666666666

In this case we have third parameter that is send out and we get the result 5/6 =0.6666666666


Congratulations, you got + 5 EXP

image


Interesting stuff, huh?! Now the time comes to unleash the true power of destructuring - destructuring with objects. Below, we have two objects:


const personOne = {
name: 'Jony',
age: 30,
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

const personTwo = {
name: 'Sally',
age: 19,
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}


Let’s use our new super skill to get name and age from our second person. It works similarly to an array:

const { name, age } = personTwo
console.log(name)//Sally
console.log(age)//19


To destructure an object we have to use curly brackets instead of square brackets. Next, we put the name of the property and make it equal to the object that we want to destructure.


The difference between destructuring an array and an object is that in the first case (array) it is based on position ( 1st, 2nd, 3th … nth), and in the second (object), destructuring is based on the name of the key (name, age). So when working with objects names should match.


What if we would like to set another key name to one of our key names, for example, so that our name would be actually - firstName?

const personTwo = {
name: 'Sally',
age: 19,
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}

const { name: firstName, age } = personTwo
console.log(firstName)//Sally
console.log(age)//19

All what is needed is to take property name and map our new variable to it - firstName.


And guess what? We can still use default values, YAY!

const personTwo = {
name: 'Sally',
age: 19,
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}

const { name: firstName, age, favoriteFood = 'Rice' } = personTwo
console.log(firstName)//Sally
console.log(age)//19
console.log(favoriteFood)//Rice

You can see that we added a property favoriteFood and set it to ‘Rice‘ , even though our object doesn’t have it.


const personTwo = {
name: 'Sally',
age: 19,
favoriteFood: 'Watermelon',
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}

const { name: firstName, age, favoriteFood = 'Rice' } = personTwo
console.log(firstName)//Sally
console.log(age)//19
console.log(favoriteFood)//Watermelon

In case, favoriteFood was specified (for example - Watermelon), then this value will be used insted of default value.


And guess what! It is also possible to use the spread operator:

const personTwo = {
name: 'Sally',
age: 19,
favoriteFood: 'Watermelon',
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}

const { name: firstName, ...rest } = personTwo
console.log(firstName)//Sally
console.log(rest)

rest is the name that we choose to call all the rest of the items besides the name, which is already included.


Now, let’s imagine that we need to pull out an item from an object inside of an object, in our case - state or city?

const personTwo = {
name: 'Sally',
age: 19,
favoriteFood: 'Watermelon',
address: {
  city:'Somewhere else',
  state: 'Another one of them'
 }
}

const { name: firstName, adress: { city } } = personTwo
console.log(firstName)//Sally
console.log(city)//Somewhere else

Super easy, all is needed is to specify the key, open curly brackets, and put the value.


Congratulations, you got + 5 EXP

image


So far so good, isn’t it? ✨


But wait, there is more to it! Do you remember that we had two objects? What if we would like to combine them using destructuring?

const personOne = {
name: 'Jony',
age: 30,
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

const personTwo = {
age: 19,
favoriteFood: 'Watermelon',
}

const personThree = {...presonOne, ...personTwo)
console.log(personThree)//name: "Jony", age: 19, adress: { city:'Somewhere', state: 'One of them'}, favoriteFood: "Watermelon"


You see, it is easy now 😃 We just have to use the spread operator. Create a new array and put the two arrays into it. Note that if personTwo has the some of the fields identical to personOne , then it will overwrite it. In our case both objects have age fields, so the value of person two age fields will be taken:

console.log(personThree)//name: “Jony“, age: 19, adress: {}…


Finally, the place where destructuring really shines - inside of the function’s arguments.

Let’s start with our personOne object and the newly created function printUser that is calling this object. As you can see when we call our new function it will return the whole object - name, age and address .

const personOne = {
name: 'Jony',
age: 30,
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

function printUser(user){
cosole.log(user)
}

printUser(personOne)//{name: 'Jony', age: 30,address: { city:'Somewhere', state: 'One of them' }}


But what if we only need name and age? We could do something like this:

const personOne = {
name: 'Jony',
age: 30,
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

function printUser(user){
cosole.log(`Name is: ${user.name}. Age is ${user.age}`)
}

printUser(personOne)//Name is Jony. Age is 30

Note that we are using ` and not ‘ or “. Also, ${} is used to add values to a string.


Using destructuring, we can choose what elements to extract:

const personOne = {
name: 'Jony',
age: 30,
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

function printUser({name, age, favoriteFood = 'Watermelon'}){
cosole.log(`Name is: ${name}. Age is ${age}. Food is ${favoriteFood}`)
}

printUser(personOne)//Name is Jony. Age is 30. Food is Watermelon.

As you can see, now we can even use default values (favoriteFood = 'Watermelon'). Now the quesiton, what if we add favoriteFood inside our object and make it apple , what will be the last sentence? If you know the answer, write it in the comments!

const personOne = {
name: 'Jony',
age: 30,
favoriteFood: 'Apple', 
address: {
  city:'Somewhere',
  state: 'One of them'
 }
}

function printUser({name, age, favoriteFood = 'Watermelon'}){
cosole.log(`Name is: ${name}. Age is ${age}. Food is ${favoriteFood}`)
}

printUser(personOne)//Name is Jony. Age is 30. Food is ??? 


Congratulations, you got + 5 EXP.


Good job, you have earned 19 EXP for this topic!

image

react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!