THAPA TECHNICAL

HOUSE OF WEB DEVELOPERS AND TECHNOLOGY.

Array destructuring in JavaScript

Array destructuring is a feature in JavaScript that allows you to extract values from an array and assign them to variables in a more concise and convenient syntax. Here's an example:


const colors = ['red', 'green', 'blue']; const [firstColor, secondColor, thirdColor] = colors; console.log(firstColor); // Output: "red" console.log(secondColor); // Output: "green" console.log(thirdColor); // Output: "blue"


In this example, the const keyword is used to declare variables firstColor, secondColor, and thirdColor. The values of these variables are extracted from the colors array using array destructuring syntax, which is enclosed in square brackets ([]). The variables are assigned the values of the corresponding elements in the array.


You can also use array destructuring to extract only the values that you need, and you can use the rest operator (...) to extract the remaining values into a new array:


const colors = ['red', 'green', 'blue', 'yellow', 'orange']; const [firstColor, secondColor, ...rest] = colors; console.log(firstColor); // Output: "red" console.log(secondColor); // Output: "green" console.log(rest); // Output: ["blue", "yellow", "orange"]

I hope you understand :) Let me know in the comment section.