Destructuring in JavaScript helps you to extract individually selected values from arrays or individually selected properties from objects and assign them to variables. Following examples demonstrate different use cases of destructuring:
- Destructuring in JavaScript : Objects
const person = {
name: 'Coding is Simple',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
const { name, age } = person;
console.log(name); // Output: Coding is Simple
console.log(age); // Output: 30
In this example, we extract the name
and age
properties from the person
object and assign them to variables of the same name.
- Destructuring in Javascript: Array
const numbers = [21, 22, 23, 24, 25];
const [twentyOne, twentyTwo, ...rest] = numbers;
console.log(twentyOne); // Output: 21
console.log(twentyTwo); // Output: 22
console.log(rest); // Output: [23, 24, 25]
Here, we extract the first two elements from the numbers
array and assign them to variables twentyOne
and twentyTwo
. The rest of the elements are gathered into an array called rest
. The rest operator ...rest
collects the remaining elements (23
, 24
, and 25
) into a new array called rest
.
Also read spread Operator in javascript
Also read rest parameter and spread operator in javascript
- Destructuring in Javascript with Default Values:
const person = {
name: 'Coding is Simple',
age: 30
};
const { name, occupation = 'Developer' } = person;
console.log(name); // Output: Coding is Simple
console.log(occupation); // Output: Developer
In this example, we extract the name
property from the person
object and assign it to the name
variable. We also define a default value of 'Developer'
for the occupation
property in case it is not present in the person
object.
- Destructuring Function Parameters in Javascript:
function greet({ name, age }) {
console.log(`Hello ${name}! You are ${age} years old.`);
}
const person = {
name: 'Coding is Simple',
age: 30
};
greet(person); // Output: Hello Coding is Simple! You are 30 years old.
Here, the greet
function expects an object parameter with name
and age
properties. Instead of passing the entire person
object, we can destructure it directly in the function parameter, accessing the values within the function body.
Destructuring provides a concise way to extract values and make code more readable and expressive. It simplifies working with complex data structures and reduces the need for manual property or element access.
- Destructuring Nested Objects:
const user = {
name: 'Coding is Simple',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
const { name, address: { city } } = user;
console.log(name); // Output: Coding is Simple
console.log(city); // Output: New York
In this example, we destructure the name
and city
properties from the user
object, which has a nested address
object. By specifying address: { city }
, we access the city
property inside the address
object directly.
- Destructuring Arrays in Function Parameters in javascript:
function getStats(numbers) {
const [min, max, average] = numbers;
console.log(`Min: ${min}, Max: ${max}, Average: ${average}`);
}
const stats = [5, 10, 7];
getStats(stats); // Output: Min: 5, Max: 10, Average: 7
In this example, the getStats
function expects an array parameter with three elements representing minimum, maximum, and average values. By using array destructuring in the function parameter, we can directly assign these values to the min
, max
, and average
variables within the function.
- Destructuring nested arrays in javascript.
const numbers = [1, 2, [3, 4, [5, 6]]];
const [a, b, [c, d, [e, f]]] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
console.log(d); // Output: 4
console.log(e); // Output: 5
console.log(f); // Output: 6
In this example, we have a nested array numbers
that contains multiple levels of nesting. By using array destructuring, we can extract the values from each level of the nested array and assign them to separate variables.
The outermost level of the numbers
array is destructured into a
and b
. The second level, [3, 4, [5, 6]]
, is destructured into c
, d
, and [e, f]
. Finally, the innermost level, [5, 6]
, is destructured into e
and f
.
By destructuring nested arrays, we can easily access and work with the values at different levels of nesting without the need for manual indexing or nested array access.
- Destructuring when importing in javascript
Destructuring can also be used when importing values from modules in JavaScript. This allows you to selectively import only the specific values you need from a module, rather than importing the entire module.
// math.js module
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
In this example, we have a module named math.js
that exports two functions: add
and subtract
. In the main.js
file, we use destructuring to import only the add
and subtract
functions from the math.js
module.
By using destructuring during the import statement, we can directly use the imported functions without needing to reference the module name. This results in cleaner and more concise code.
Note that when using destructuring during imports, the imported names must match the exported names from the module. Otherwise, an error will occur.