0% found this document useful (0 votes)
9 views1 page

How Array Destructuring Works

Array destructuring in JavaScript allows for variable assignment based on array positions, skipping values with commas, and capturing remaining elements using the rest parameter. Default values can be assigned for undefined elements, and it also enables easy swapping of variable values. This technique enhances code readability and efficiency.

Uploaded by

saifahmedm24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

How Array Destructuring Works

Array destructuring in JavaScript allows for variable assignment based on array positions, skipping values with commas, and capturing remaining elements using the rest parameter. Default values can be assigned for undefined elements, and it also enables easy swapping of variable values. This technique enhances code readability and efficiency.

Uploaded by

saifahmedm24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

How Array Destructuring Works:

Basic Assignment: Values are assigned to variables based on their position in the
array.
JavaScript

const numbers = [10, 20, 30];


const [first, second, third] = numbers;

console.log(first); // Output: 10
console.log(second); // Output: 20
console.log(third); // Output: 30
Skipping Values: Commas can be used to skip elements in the array.
JavaScript

const fruits = ["Apple", "Banana", "Cherry", "Date"];


const [fruit1, , fruit3] = fruits; // Skips "Banana"

console.log(fruit1); // Output: Apple


console.log(fruit3); // Output: Cherry
Rest Parameter: The rest parameter (...) can be used to capture remaining elements
into a new array.
JavaScript

const data = [1, 2, 3, 4, 5];


const [a, b, ...restOfData] = data;

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(restOfData); // Output: [3, 4, 5]
Default Values: Default values can be provided for variables in case the
corresponding array element is undefined.
JavaScript

const colors = ["Red", "Green"];


const [color1, color2, color3 = "Blue"] = colors;

console.log(color1); // Output: Red


console.log(color2); // Output: Green
console.log(color3); // Output: Blue
Swapping Variables: Destructuring provides a clean way to swap variable values
without a temporary variable.
JavaScript

let x = 5;
let y = 10;
[x, y] = [y, x];

console.log(x); // Output: 10
console.log(y); // Output: 5

You might also like