DEV Community

loading...
Cover image for Mastering JavaScript Destructuring

Mastering JavaScript Destructuring

kalashin1 profile image Kinanee Samson ・6 min read

Good day guys, in this article we are going to be talking in detail about destructuring in JavaScript. By the way, what the heck is destructuring? Destructuring is just a fancy word for used to describe the process of unpacking values from an array or object into variables. Destructuring is a cool feature of ES6 flavour of JavaScript and you might have seen this been used a lot. If you always wondered what this means or how to use it in your code then worry no more because by the end of this article, you will have gained a basic understanding of how destructuring works in JavaScript and you will be able to use it in your code, destructuring your objects and arrays like a god. If you already know a lot about destructuring then feel free to leave a comment or two that will further clarify the subject in areas I did not. Well then let's dive in.

What is Destructuring?

Like we said earlier, destructuring is the process of unpacking values from an object or an array into distinct variables. Destructuring was introduced into JavaScript with the syntax upgrade that came with ECMA Script 6 to JavaScript and what destructuring does is to eliminate the boring and repetitive process of calling object name and then the key multiple times when we want to extract the values inside the object or in an array. Here is a clearer picture of what i mean, before Destructuring we used to extract the properties of an object or an array like this;


const hero = {
    name: 'john doe',
    age: 25,
    gender: 'male',
    email: 'johndoe@gmail.com'
}

const name = hero.name
const age = hero.age
const gender = hero.gender
const email = hero.email


// or 
const arr = ['superman', 'batman', 'cyborg', 'aquaman']

const superman = arr[0]
const batman = arr[1]
Enter fullscreen mode Exit fullscreen mode

This was the standard old way of obtaining the keys inside an object or the values stored inside an array. This method of doing things is quite fine but there is some drawbacks associated with it.

  • We have to repeat the object name or the array name anytime we want to extract a key or value from it and this can lead to potential typos.
  • This also takes up unnecessary lines in our code, bloating and elongating our code for no reason.

To address this, destructuring was introduced, and the rest is like magic. What would have taken up like 4 to five lines can now take only one line, keeping our code short and clean. There are two types of destructuring;

  • Array destructuring
  • Object destructuring

Array Destructuring

Let us get our hands dirty with array destructuring, we can use this method to assign values to variables in our code

const arr = [1, 2, 3]

const [num1, num2, num3] = arr

console.log(num1, num2, num3) // 1, 2, 3
Enter fullscreen mode Exit fullscreen mode

And that is it, we have successfully destructured the array above, what we would have done in like three lines of code is now done with only one, to destructure an array we simply wrap the variable we would like to hold the values that are inside the array we are destructuring in square brackets. Just like we did above. One thing to take note is that the values inside the array will be destructured into the variables based on how we arrange them when use the destructuring syntax, this

const arr = [1, 2, 3]

const [num1, num2, num3] = arr

// num1 = arr[0]
// num2 = arr[1]

console.log(num1, num2, num3) // 1, 2, 3
Enter fullscreen mode Exit fullscreen mode

Incase you missed it, this way of destructring is called assingment destructuring. In the above example we are assuming that the array will only hold 3 values, one cool thing about destructuring is that we can destructure the array to only just what we need from it and forget about the rest.

const arr [ 1, 2, 3, 4, 5, 6, 7 ]

const [num1, num2, num3] = arr

console.log(num1, num2, num3) //1 , 2, 3
Enter fullscreen mode Exit fullscreen mode

We can also skip one item and go on to the next, or skip multiple item. We simply use a comma without any variable before it to skip that particular value if we are not too interested in obtaining that value from the array.

const arr = [ 1, 2, 3, 4, 5, 6, 7 ]

const [num1, num2, , num4] = arr

console.log(num1, num2, num3) //1 , 2, 4
Enter fullscreen mode Exit fullscreen mode

We can also create an array from the remaining the values we did not destructure, we use the spread syntax to achieve this. It takes whatever is left of the array that we did not destructure into a new array.

const arr = [ 1, 2, 3, 4, 5, 6, 7 ]

const [num1, num2, ...rest] = arr

// puts the rest of arr into rest

console.log(num1, num2, rest) 
// 1, 2, [3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

We can also use array destructuring to swap the values of variables, ordinary without destructuring we would need a third variable and many unnecessary lines of code, but destructuring eliminates all this problems.

const num1 = 1
const num2 = 2

console.log(num1, num2) // 1, 2

[ num1, num2 ] = [ num2, num1 ]

console.log(num1, num2) // 2, 1
Enter fullscreen mode Exit fullscreen mode

If we have a function that accepts many parameters we can simply rewrite it to accept only one parameter which will be an array, we can then destructure the array to obtain the values we need, we can also use it when we want to extract multiple values returned from a function.

// original function without destructuring
function doSomething(param1, param2, param3, param4) {
    // do something with param1, param2, param3, param4
    console.log(param1, param2, param3, param4)
}

// using destructuring
function doSomething(params){
    const [param1, param2, param3, param4] = params
    console.log(param1, param2, param3, param4)
}

// dealing with functions that returns multiple values
function returnManyStuffs(arg){
    const val = arg
    return [
        () => arg,
        (_val) => val = _val
    ]
}

const [val, setVal] = returnManyStuffs(10)

console.log(val) // 10
Enter fullscreen mode Exit fullscreen mode

What if you want to destructure something that's undefined?

const arr = [ 12, 24 ]

const [num1, num2, num3=48] = arr

console.log(num1, num2, num3)
Enter fullscreen mode Exit fullscreen mode

Object Destructuring

We can do assignment destructuring with objects much like we did with arrays

const subject = {
    name: 'maths',
    creditUnit: 2,
    lecturer: 'mr Smart'
}

const { name, creditUnit, lecturer } = subject

console.log(name, creditUnit, lecturer) // maths, 2, mr Smart
Enter fullscreen mode Exit fullscreen mode

One thing with object destructuring, the name of the variable should match the name of the key we are trying to destructure on the object. But sometimes that might throw an error in our code because we might already have a variable with that name, we want to destructure a key on the object but we want to call it something else.

const subject = {
    name: 'maths',
    creditUnit: 2,
    lecturer: 'mr Smart'
}

const { name: subjectName, creditUnit, lecturer } = subject

console.log( subjectName, creditUnit, lecturer ) // maths, 2, mr Smart
Enter fullscreen mode Exit fullscreen mode

We can also pack the rest properties on the object into another object like we did with the array

const subject = {
    name: 'maths',
    creditUnit: 2,
    lecturer: 'mr Smart',
    materials: {
        textBook: 'intro to maths',
        graphBook: 'some graph'
    }
}

const { name, creditUnit, ...others} = obj

console.log(name, creditUnit, others )
// maths, 2, { lecturer: 'mr Smart', materials: { textBook: 'intro to maths', graphBook: 'some graph'}}
Enter fullscreen mode Exit fullscreen mode

We can also rewrite our function to accepts objects and destructure the object inside the function, we can also return multiple values from a function using objects and we can destructure that return value to get just what we want.

function doSomething(params){
    const { val1, val2, val3 } = params
    // do something with val1, val2, val3
}

function makeObj(){
    return { name: 'foo', job: 'coding'}
}

const { name, job } = makeObj()

console.log(name, job) // foo coding
Enter fullscreen mode Exit fullscreen mode

We can also provide default values incase we are trying to destructure something that's undefined on the object.

const obj = { name: 'john', age: 25}

const { name, age, job = 'coding' } = obj

console.log(name, age, job) // john, 25, coding
Enter fullscreen mode Exit fullscreen mode

Deep Structuring

You can also destructure deeply nested objects and arrays, let's see how we can destructure this big object

const club = { 
    name: 'liverpool',
    location: 'england',
    coach: 'jurgen klopp',
    stadium: {
        name: 'anfield',
        location: 'mersyside' 
    },
    squad: {
        captain: 'jordan henderson',
        goalies: ['becker', 'adrian']
    }
}

const {  
    stadium: {
        name: stadiumName
    },
    squad: {
        captain,
        goalies
    }
} = club

console.log( stadiumName, captain ) // anfield, jordan henderson, ['becker', 'adrian']
Enter fullscreen mode Exit fullscreen mode

That's it for this article, i hope you found this useful, feel free to leave a comment below and like the post. You can read more about destructuring here or if you prefer to watch a video you can head here

Discussion (0)

Forem Open with the Forem app