Destructuring
Destructuring lets you quickly pull values out of arrays or objects into separate variables when you create them.
In Varjus, destructuring works only during variable initialization — you can’t apply it to variables that already exist.
For arrays, you can extract items from the first level, and use the rest operator ...
to collect remaining items into one variable:
Here's an example without destructuring:
//arrays
const numbers = [10, 20, 30];
const first = numbers[0]; // first = 10
const second = numbers[1]; // second = 20
//objects
const person = {name: "Alice", age: 25, city: "NY"};
const personName = person.name; // personName = "Alice"
const personAge = person.age; // personAge = 25
This works, but it can get repetitive and long if you need many values. With destructuring, you can extract many values in one line when you create variables.
Array Destructuring
You use square brackets []
on the left side to match the structure of the array.
const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first = 10
// second = 20
// rest = [30, 40, 50]
Object Destructuring
You use curly braces {}
on the left side and list the property names you want.
const {name, age} = {name: "Alice", age: 25, city: "NY"};
// name = "Alice"
// age = 25
// city is ignored
Here you pick which properties to extract by their names. Properties you don’t list are not included.
Destructuring in Loops
You can also use destructuring in ranged-for loops to directly access parts of arrays or objects while iterating:
Looping Over Arrays
for (const [x, y, z] : coordinates) {
console.log(x, y, z);
}
Here, each item is an array [x, y, z] and destructuring pulls those three values into variables.
Looping Over Objects
If you have object entries (like key-value pairs), you can destructure them too:
//assuming objectEntries is an array of objects (objects aren't iterable)
for (const {key, value} : objectEntries) {
console.log(key, value);
}