Skip to Content
Course content

41: Destructuring Objects and Arrays

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why should I use destructuring instead of just using dot notation?

Honestly, if you're only grabbing one property from an object, dot notation is perfectly fine. But once you start pulling three, four, or five properties out of a config object or an API response, your code starts looking like a shopping list of repetitions. It gets noisy.

Take a user profile, for example. Without destructuring, you're doing this:

const user = { id: 1, username: 'dev_jane', email: 'jane@example.com', theme: 'dark' };

const username = user.username;
const email = user.email;
const theme = user.theme;

It's tedious. With destructuring, we can collapse that into a single line. I do this constantly because it makes the intent of the code much clearer: "I need these specific pieces of data from this object."

const { username, email, theme } = user;

What if the property is missing or I want to call the variable something else?

This is where destructuring actually becomes a tool for safety, not just a shorthand. When you're dealing with external data, you can't always guarantee a field exists. You can set a default value right inside the curly braces.

Also, sometimes the API gives you a property name that is generic or clashes with a variable you already have. You can rename it using a colon.

const apiResponse = { 
  title: 'JavaScript Deep Dive', 
  author: 'Sarah Drasner' 
};

// Rename 'title' to 'bookTitle' and provide a default for 'year'
const { title: bookTitle, year = 'Unknown Year' } = apiResponse;

console.log(bookTitle); // 'JavaScript Deep Dive'
console.log(year);      // 'Unknown Year'

Can I use this directly in function parameters?

Yes, and in my experience, this is where you'll use it 90% of the time in modern frameworks like React. Instead of passing a giant object into a function and then extracting what you need inside the function body, you can destructure the argument list itself.

Look at the difference here. We're building a small helper to format a product price:

// The old way
function printPrice(product) {
  console.log(`${product.name} costs ${product.price}`);
}

// The professional way
function printPrice({ name, price }) {
  console.log(`${name} costs ${price}`);
}

const laptop = { name: 'MacBook Pro', price: 2499, sku: 'MBP-14' };
printPrice(laptop);

By destructuring in the signature, anyone reading your function knows exactly which properties the function expects without having to hunt through the function body.

How does this work with arrays since they don't have keys?

Array destructuring is based on position rather than property names. It's incredibly useful when a function returns multiple values (usually in the form of an array). You just name the variables whatever you want, and JS maps them to the index.

I often use this when dealing with coordinates or when I only care about the first few elements of a list. You can also use the "rest" operator (three dots) to gather the remaining elements into a new array.

const coordinates = [40.7128, -74.0060, 'North America', 'UTC-5'];

const [lat, lng, ...metadata] = coordinates;

console.log(lat);       // 40.7128
console.log(lng);       // -74.0060
console.log(metadata);  // ['North America', 'UTC-5']



📋 Practical Task

Exercise: Refactoring the Game Character Stats Parser

You have been handed a legacy function that processes player data for a role-playing game. Currently, it uses old-school dot notation and is very repetitive. Your task is to refactor the displayPlayerStats function using object destructuring in the parameter list and array destructuring for the inventory list.

Requirements:

  • Destructure name, level, and health directly in the function parameters.
  • Provide a default value of 100 for health in case it's missing from the object.
  • Inside the function, destructure the inventory array to extract the first item as primaryWeapon and the rest of the items as otherGear.
  • Log a string that looks like: "Player Jane (Lvl 10) has 100 HP. Weapon: Sword. Other gear: [Shield, Potion]"
const player = {
  name: 'Jane',
  level: 10,
  inventory: ['Sword', 'Shield', 'Potion', 'Map']
  // health is missing here to test your default value
};

function displayPlayerStats(player) {
  // Your refactored code here
}

displayPlayerStats(player);
Rating
0 0

There are no comments for now.

to be the first to leave a comment.