KandZ – Tuts

We like to help…!

JavaScript 24 🧬 Destructuring

a - intro and array destructuring
Destructuring assignment in JavaScript is a feature that allows you to extract data from arrays or objects into variables
It uses a syntax that looks similar to array or object literal notation.
This can make your code more concise and readable.
Array Destructuring:
const [a, b, c] = [1, 2, 3]; → unpacks array to a, b, c variables
const [x, , y] = [4, 5, 6]; → unpacks array and skipping the 2nd value
const [p, q = 10] = [7]; → sets a default value

b - object destructuring
Destructuring is a powerful feature that can make your code cleaner and more expressive.
It is widely used in modern JavaScript development....
especially with libraries like React where it simplifies the extraction of props and state.
const { name, age } = { name: 'Alice', age: 25 }; → unpacks the object to name and age properties
const { firstName: fn, lastName: ln, middleName = 'M' } = { firstName: 'John', lastName: 'Doe' };
renames the variables and uses default values
const { name, address: { city, zip } } = user; → Nested Destructuring
function displayInfo({ name, age }) {} → Function Parameter Destructuring

Leave a Reply