DEV Community

Cover image for Destructuring in JavaScript
Mahmoud Elmahdi
Mahmoud Elmahdi

Posted on

Destructuring in JavaScript

Destructuring assignment is one of the most flexible, simplest feature in modern JavaScript. It's a JavaScript expression that makes it possible to unpack values from Arrays, properties from Objects, or even Function params, into distinct variables.

Destructuring objects

We often reference to the same variable in several places in our codebase and we'd prefer to avoid declaring out the same variable over the over again. For instance, making requests to the server might require an authorization (token) in the header's request. Assume we have a session object the holds token and refresh_token keys for instance


const token = session.token;
const refreshToken = session.refresh_token;
Enter fullscreen mode Exit fullscreen mode


const {
  token,         // ↓ alias ↓
  refresh_token: refreshToken
} = session;
Enter fullscreen mode Exit fullscreen mode

In the ES6 snippet above, the syntax becomes more clear. Just like you could declare multiple comma-separated variables with a single let statement, you can also declare multiple variables within curly braces of a destructuring expression. Also there are cases where we want to rename the property name into different one; in that case, you'll use a : amAlias . Above we used alias to change the property name from snake-case to camelCase.

Function parameter

We can use destructuring in function parameters to unpack fields from objects passed as function parameter. If we wanted to implement a function that only takes into account certain properties of parameter, it might be a good idea to reference those properties explicitly by destructuring up front. Destructure everything up front, makes it easy to spot when input doesn't adhere to the contract of a function.

const getFullName = ({ user }) => 
  user && `${user.firstName} ${user.lastName}`;

const state = {
    user: {
        firstName: 'Mahmoud',
        lastName: 'Elmahdi'   

getFullName(state); // Mahmoud Elmahdi
Enter fullscreen mode Exit fullscreen mode

Parsing a returned value from a function

Whenever there’s a function that returns an object or an array, destructuring can make working with that returned value more concise to interact with. The following example shows a getUser function that returns an object with user's data, where we grab only the ones we're interested in: isAdmin and ignore the rest

const getUser = () => ({
    id: 156,
    isAdmin: true,
    fullName: 'Mahmoud Elmahdi',
    email: '',
    languages: ['Arabic', 'English', 'Russian']

const { isAdmin } = getUser();
isAdmin && retrieveSensitiveData();
Enter fullscreen mode Exit fullscreen mode

Array destructuring

Destructuring arrays uses square brackets instead of curly braces. Instead of having to sprinkle your code with implementation details like x = arr[0], with destructuring you can convey your meaning clearly and without explicitly referencing the indices, naming the values instead

Destructuring arrays

When destructuring arrays, we also can skip those properties we don't need to reference to

Destructuring arrays

Useful tips

Add properties conditionally inside object literals with spread operator for properties:

Add properties conditionally

Add elements inside array literals only if the element is true (not null/undefined or empty)

Add elements inside array literals

Discussion (5)

dance2die profile image
Sung M. Kim

Thanks Mahmoud. It was easy to digest the content.

Array destructuring section will help for those who are unfamiliar with new useState React hook (preview) as it uses array destructuring.

const [state, setState] = useState(initialState);
okbrown profile image
Orlando Brown • Edited on

Hi, I'm not sure about this... Please explain how this works.

const mood = {
   ...isWeekend ? {} : {}

How does one spread a Boolean?
Should this not be

const mood = {
   isWeekend ? ...{} : ...{}
_elmahdim profile image
Mahmoud Elmahdi Author • Edited on

the isWeekend flag holds a boolean value (which is condition not the key), and based on that we decide which key property (music or routine) to add to the mood object, and since the Spread operator (three dots ...) allows us to add/concat things into object and array literals that was the point of using it! is to add the desirable key conditionally.

If you try to execute your second snippet

const mood = {
   isWeekend ? ...{} : ...{}

You'll get syntax error.

I create a demo for the same logic in ES6 and its equivalent in ES5.

I hope that answers your question.

ogaston profile image
Omar Gaston Chalas

I really love how easy is "get-out" one property in js. Thanks for sharing

meddjelaili profile image
Mohamed Djelaili

thanks for sharing Mahmoud