JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects
Destructuring
In this lesson8
A report from the Jurassic Park lab is an object full of data: vital signs, GPS coordinates, DNA analysis results. To do anything with it, you have to pull values out one by one: report.vitals.heartRate, report.location.zone and so on, over and over again. "Destructuring is like sorting DNA samples," says Dr. Rex. "Instead of pulling out every test tube by hand, you take exactly the data you need in one move."
Object Destructuring - Basics
Object destructuring pulls an object's properties into separate variables in a single line. Compare the two versions:
1const dinosaur = {
2 name: 'Rex',
3 species: 'Tyrannosaurus',
4 weight: 8000,
5 zone: 'A'
6};
7
8// Without destructuring
9const name1 = dinosaur.name;
10const weight1 = dinosaur.weight;
11
12// With destructuring - much shorter!
13const { name, species, weight, zone } = dinosaur;
14console.log(name); // "Rex"
15console.log(species); // "Tyrannosaurus"
16console.log(weight); // 8000The braces on the left of the = sign do not create a new object. They are a pattern that says: "create variables with these names and put the values of the properties with the same names into them". The dinosaur object stays intact; nothing is removed from it or added to it.
Renaming Variables (Alias)
Sometimes a property name clashes with an existing variable or is simply unclear. Then you give a new name after a colon. You also do not have to pull out every property, only the ones you need:
1const { name: dinoName, zone: dinoZone } = dinosaur;
2console.log(dinoName); // "Rex"
3console.log(dinoZone); // "A"Only the variables dinoName and dinoZone were created. This line does not create name or zone, because the name before the colon only points to the property being read. You can use several aliases at once:
1const sensor = { id: 'S-001', value: 42.5, status: 'active' };
2
3// Renaming the variables
4const { id: sensorId, value: reading, status: sensorStatus } = sensor;
5console.log(sensorId); // "S-001"
6console.log(reading); // 42.5
7console.log(sensorStatus); // "active"Read the colon as "store in": id: sensorId means "take id and store it in sensorId".
Default Values
If a property is missing from the object, you can set a default value after an = sign. An alias and a default value combine in one entry:
1const specimen = { name: 'Blue', species: 'Velociraptor' };
2
3// health does not exist in the object - use the default value
4const { name: specimenName, health = 100, zone: specimenZone = 'Unknown' } = specimen;
5console.log(specimenName); // "Blue"
6console.log(health); // 100 (default)
7console.log(specimenZone); // "Unknown" (default)A default value only applies when the property is missing or holds undefined. If the object had health: 95, you would get 95, and with health: null you would get null, because null is a value someone set on purpose.
Nested Destructuring
Objects often contain nested structures, and destructuring lets you reach deep inside by repeating the shape of the object:
1const dinoReport = {
2 name: 'Rex',
3 vitals: {
4 heartRate: 65,
5 temperature: 37.2,
6 bloodPressure: { systolic: 120, diastolic: 80 }
7 },
8 location: { zone: 'A', sector: 3 }
9};
10
11// Nested destructuring
12const {
13 name: reportName,
14 vitals: { heartRate, temperature },
15 location: { zone: reportZone, sector }
16} = dinoReport;
17
18console.log(reportName); // "Rex"
19console.log(heartRate); // 65
20console.log(temperature); // 37.2
21console.log(reportZone); // "A"
22console.log(sector); // 3Watch out for a common mistake: vitals: { heartRate } does not create a vitals variable; it only marks the path to heartRate. If the report had no vitals, you would get a TypeError. That is why I recommend going at most two levels deep, because deeper patterns are hard to read.
Array Destructuring
Arrays are destructured with square brackets. Here position matters, not names, so you can name the variables however you like:
1const dnaSequence = ['A', 'T', 'C', 'G', 'T', 'A'];
2
3// Extract the first three elements
4const [first, second, third] = dnaSequence;
5console.log(first); // "A"
6console.log(second); // "T"
7console.log(third); // "C"
8
9// Skipping elements using commas
10const [, , thirdNucleotide, , fifthNucleotide] = dnaSequence;
11console.log(thirdNucleotide); // "C"
12console.log(fifthNucleotide); // "T"Each empty comma skips one position. In const [a, , b] = ['Rex', 'Blue', 'Delta'] the variable a gets 'Rex', 'Blue' is skipped and b gets 'Delta'.
Swapping Variables
Array destructuring lets you elegantly swap two variables without a temporary variable, for example when two dinosaurs trade paddocks:
1let zoneA = 'Rex';
2let zoneB = 'Blue';
3
4// Swap values
5[zoneA, zoneB] = [zoneB, zoneA];
6console.log(zoneA); // "Blue"
7console.log(zoneB); // "Rex"The right side creates a temporary array ['Blue', 'Rex'], and the left side unpacks it immediately. Mind the semicolon on the previous line: without it, a line starting with [ merges with the line above and the swap ends in an error.
Default Values in Arrays
Arrays accept default values too. When the GPS sensor sends only one coordinate, the second one gets a fallback value:
1const coordinates = [12.5];
2const [latitude, longitude = 0] = coordinates;
3console.log(latitude); // 12.5
4console.log(longitude); // 0 (default)Position 1 does not exist in the array, so longitude gets 0 instead of undefined.
Destructuring in Function Parameters
Destructuring is especially useful in function parameters. The function takes an object and immediately picks the fields it needs:
1// Object destructuring in a parameter
2function displayDino({ name, species, weight = 'unknown' }) {
3 console.log(`${name} (${species}) - ${weight} kg`);
4}
5
6displayDino({ name: 'Rex', species: 'T-Rex', weight: 8000 });
7// "Rex (T-Rex) - 8000 kg"
8
9displayDino({ name: 'Blue', species: 'Velociraptor' });
10// "Blue (Velociraptor) - unknown kg"
11
12// Array destructuring in a parameter
13function processCoords([lat, lon]) {
14 console.log(`Latitude: ${lat}, Longitude: ${lon}`);
15}
16
17processCoords([12.345, 67.890]);
18// "Latitude: 12.345, Longitude: 67.89"The order of fields in the passed object does not matter, and the call describes itself. That is why I recommend this style when a function has more than two parameters. Notice also that the number 67.890 prints as 67.89, because converting a number to text drops trailing zeros. Calling displayDino() with no argument throws a TypeError, so when the object is optional, add a default = {} after the pattern.
Combining Destructuring with Rest
The ... operator collects the "rest" of the elements into a new array or a new object:
1const allSpecies = ['T-Rex', 'Velociraptor', 'Triceratops', 'Brachio', 'Stego'];
2
3const [firstSpecies, secondSpecies, ...otherSpecies] = allSpecies;
4console.log(firstSpecies); // "T-Rex"
5console.log(secondSpecies); // "Velociraptor"
6console.log(otherSpecies); // ["Triceratops", "Brachio", "Stego"]
7
8// Rest in objects
9const fullDino = { name: 'Rex', species: 'T-Rex', weight: 8000, zone: 'A', health: 95 };
10const { name: restName, ...dinoStats } = fullDino;
11console.log(restName); // "Rex"
12console.log(dinoStats); // { species: "T-Rex", weight: 8000, zone: "A", health: 95 }Rest must come last in the pattern, and fullDino still has all five properties. In the next lesson you will see that the same three dots can also unpack data.
Practice
The sandbox contains object destructuring, aliases with default values and a nested report. Add your own patterns and check in the console which variables were created.
Code for this lesson: index.js
1// === OBJECT AND ARRAY DESTRUCTURING ===
2
3// 1. Object destructuring
4const dinosaur = { name: 'Rex', species: 'Tyrannosaurus', weight: 8000, zone: 'A' };
5const { name, species, weight } = dinosaur;
6console.log('=== Object ===');
7console.log('Name:', name, '| Species:', species, '| Weight:', weight);
8
9// 2. Renaming (alias) and default values
10const sensor = { id: 'S-001', value: 42.5 };
11const { id: sensorId, value: reading, status: sensorStatus = 'active' } = sensor;
12console.log('\n=== Alias and default ===');
13console.log('ID:', sensorId, '| Reading:', reading, '| Status:', sensorStatus);
14
15// 3. Nested destructuring
16const report = {
17 name: 'Rex',
18 vitals: { heartRate: 65, temperature: 37.2 },
19 location: { zone: 'A', sector: 3 }
20};
21const { vitals: { heartRate, temperature }, location: { zone } } = report;
22console.log('\n=== Nested ===');
23console.log('Pulse:', heartRate, '| Temp:', temperature, '| Zone:', zone);
24
25// 4. Array destructuring
26const dna = ['A', 'T', 'C', 'G', 'T', 'A'];
27const [first, second, third] = dna;
28console.log('\n=== Array ===');
29console.log('First 3:', first, second, third);
30
31// Skipping elements
32const [, , thirdEl, , fifthEl] = dna;
33console.log('Third:', thirdEl, '| Fifth:', fifthEl);
34
35// 5. Value swapping
36let zoneA = 'Rex';
37let zoneB = 'Blue';
38[zoneA, zoneB] = [zoneB, zoneA];
39console.log('\n=== Swap ===');
40console.log('zoneA:', zoneA, '| zoneB:', zoneB);
41
42// 6. Destructuring in function parameters
43function displayDino({ name: n, species: s, weight: w = 'unknown' }) {
44 console.log(n + ' (' + s + ') - ' + w + ' kg');
45}
46console.log('\n=== Function parameters ===');
47displayDino({ name: 'Rex', species: 'T-Rex', weight: 8000 });
48displayDino({ name: 'Blue', species: 'Velociraptor' });
49
50// 7. Rest in destructuring
51const all = { name: 'Rex', species: 'T-Rex', weight: 8000, zone: 'A', health: 95 };
52const { name: dName, ...stats } = all;
53console.log('\n=== Rest ===');
54console.log('Name:', dName);
55console.log('Rest:', JSON.stringify(stats));Remember: destructuring is a sample sorting room that moves the test tubes you need onto the table in one move and leaves the original report intact.
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the expression const { name, weight } = dinosaur do?
2. What does the expression const { id: sensorId, status = 'active' } = sensor mean?
3. How do you swap the values of two variables using array destructuring?
Hands-on tasks in the game
- Code editor
You have an object const dino = { name: 'Rex', species: 'T-Rex', stats: { weight: 8000, speed: 30 } } and an array const zones = ['A', 'B', 'C', 'D']. Using object destructuring, create the variables dinoName (an alias for name), species, weight (from the nested stats) and diet with the default value 'carnivore'. Using array destructuring, create firstZone, secondZone and otherZones with the remaining elements. Also write a function describeDino({ name, species }) that destructures its parameter and returns the text name + ' (' + species + ')'.
- Vertical ordering
Arrange what will be assigned to variables in the destructuring const [a, , b] = ['Rex', 'Blue', 'Delta']:
- Click in order
Arrange the elements of nested destructuring: const { vitals: { heartRate } } = report
- Code editor
You have a report: const report = { id: 'R-7', dino: { name: 'Blue', vitals: { heartRate: 65, temperature: 37.2 } }, zone: 'B', status: 'ok' }. Using destructuring, create: id, patientName (an alias for report.dino.name), heartRate (from report.dino.vitals) and an object meta that collects the remaining top-level properties (without id and dino) with the rest operator. Also write a function formatVitals({ heartRate, temperature = 36.6 }) that returns the text heartRate + ' bpm, ' + temperature + ' C'.