Destructuring was introduced as part of ECMAScript 2015 (ES6) and provides a simple way of extracting values from objects and arrays.
It is widely used throughout modern JavaScript and is commonly found in React, React Native and Node.js applications.
Although destructuring may initially appear unusual, it often results in less code and improved readability.
What destructuring is
Destructuring allows values to be extracted from an object or array and assigned to variables.
Rather than accessing values individually, multiple values can be extracted at the same time.
Object destructuring
Consider the following object:
const user = { name: "John", age: 25 };
Traditionally, each property would be assigned separately:
const name = user.name; const age = user.age;
Destructuring provides a shorter alternative:
const { name, age } = user;
Multiple properties
Multiple properties can be extracted simultaneously.
const user = { first_name: "John", last_name: "Smith", age: 25 }; const { first_name, last_name, age } = user;
Three variables are created from a single statement.
Renaming properties
Property names and variable names do not need to be the same.
Consider the following:
const user = { first_name: "John" }; const { first_name: name } = user;
The value of first_name is assigned to the variable
name.
Default values
Default values can be provided when a property may not exist.
const user = { name: "John" }; const { name, country = "United Kingdom" } = user;
Because the country property does not exist, the default value
will be used.
Array destructuring
Arrays can also be destructured.
const colours = [ "red", "green", "blue" ]; const [ first, second ] = colours;
The variable first will contain "red" and
second will contain "green".
Skipping array elements
It is possible to ignore values that are not needed.
const [ first, , third ] = colours;
The second value is skipped and only the first and third values are extracted.
Nested destructuring
Destructuring can be used with nested objects.
const user = { profile: { name: "John", age: 25 } }; const { profile: { name } } = user;
The value of profile.name is extracted directly into a variable.
Destructuring function parameters
Destructuring can be performed directly within function parameters.
function displayUser({ name, age }){ console.log(name); console.log(age); }
This technique is frequently used in React components.
When to use destructuring
Destructuring should be used when multiple properties or array elements need to be extracted from a data structure.
It reduces repetition and often results in cleaner, easier to read code.
Since destructuring is heavily used throughout modern JavaScript, React, React Native and Node.js applications, it is an important concept to understand before moving on to more advanced topics.
