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
ES5:
const token = session.token;
const refreshToken = session.refresh_token;
ES6:
const {
token, // β alias β
refresh_token: refreshToken
} = session;
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
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: 'abracadabra@email.com',
languages: ['Arabic', 'English', 'Russian']
});
const { isAdmin } = getUser();
isAdmin && retrieveSensitiveData();
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
When destructuring arrays, we also can skip those properties we don't need to reference to
Useful tips
Add properties conditionally inside object literals with spread operator for properties:
Add elements inside array literals only if the element is true (not null
/undefined
or empty)
Top comments (5)
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.
Hi, I'm not sure about this... Please explain how this works.
How does one spread a Boolean?
Should this not be
the
isWeekend
flag holds a boolean value (which is condition not the key), and based on that we decide which key property (music
orroutine
) to add to themood
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
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.
I really love how easy is "get-out" one property in js. Thanks for sharing
thanks for sharing Mahmoud