Skip to main content

Command Palette

Search for a command to run...

Destructuring in JS

Clean, Concise Data Extraction in Modern JavaScript

Published
6 min read
Destructuring in JS

You have an object. It has properties. You want those properties as standalone variables. Before destructuring, you wrote one line per property. With destructuring, you write one line total.

That's the whole thing. It's not a new data structure. It's not magic. It's a shorter way to pull values out of objects and arrays and assign them to variables in one shot.

It showed up in ES6 (2015) and now it's everywhere. You'll see it in React, Node, API responses, config files. Once you understand it, you'll spot it in every codebase you read.

Destructuring doesn't change the original object or array. It just copies values out into new variables. The source stays exactly as it was.

Objects First

Say you have a user object. The old way was to read each property individually. Three properties meant three lines. Twenty properties meant twenty lines, all with user. repeated like a broken record

// accessing objects
const user = {
  name: "User1",
  age: 28,
  city: "Delhi"
};

const name = user.name;
const age  = user.age;
const city = user.city;

// destructuring
const user = {
  name: "User1",
  age: 28,
  city: "Delhi"
};

const { name, age, city } = user;
// same result, one line

The curly braces on the left tell JavaScript: look inside user and find properties with these names. Create variables with those names. Done. The variable names match the property names exactly, so nothing is ambiguous.

You can pull out as many or as few properties as you need. You don't have to grab all of them. If user has ten properties and you only need name and email, just write those two.

// partial destructuring
const user = {
  name: "User1",
  age: 28,
  city: "Delhi",
  email: "user1@example.com",
  role: "admin"
};

// Only pull what you need, everything else stays in user
const { name, email } = user;
console.log(name);   // "User1"
console.log(email);  // "user1@example.com"

Destructuring Arrays

Arrays work the same way. Instead of curly braces you use square brackets, and instead of matching by name you match by position. First variable gets index 0, second gets index 1, and so on.

// before
const colors = ["red", "green", "blue"];

const first  = colors[0];
const second = colors[1];
const third  = colors[2];

// after
const colors = ["red", "green", "blue"];

const [first, second, third] = colors;

// first = "red", second = "green"

You name the variables yourself here, since arrays have no property names. Whatever you write inside the brackets becomes the variable name for that slot.

You can skip positions too. Leave a blank comma where you want to skip an index.

// skip positions
const scores = [88, 72, 95, 60];

// only grab first and third
const [first, , third] = scores;

console.log(first);  // 88
console.log(third);  // 95

Default Values

Sometimes a property doesn't exist in the object, or an array slot is empty. Without a default value, you get undefined. With one, you get a sensible fallback.

// default values in object destructuring
const settings = {
  theme: "dark"
  // no `fontSize` key in this object
};

const { theme, fontSize = 16 } = settings;

console.log(theme);     // "dark"   = came from the object
console.log(fontSize);  // 16      = used the default, key was missing

The default only kicks in when the value is undefined. If the object has the key and it's set to null or 0 or even an empty string, the default is ignored and you get whatever's actually there.

// defaults in array destructuring
const rgb = [255, 128];  // only two values, third is missing

const [r, g, b = 0] = rgb;

console.log(r);  // 255
console.log(g);  // 128
console.log(b);  // 0  = default used since index 2 didn't exist

Defaults make your code defensive without adding if statements. If an API sometimes returns an object without certain fields, destructuring with defaults handles the missing data in one line instead of three.

Renaming While Destructuring

Sometimes the property name in the object clashes with a variable you already have, or it's just not a clear name for what you're doing. You can rename it right in the destructure using a colon.

const response = {
  n: "User1",   // short API field name, not readable
  a: 28
};

// n becomes name, a becomes age 
const { n: name, a: age } = response;

console.log(name);  // "User1"
console.log(age);   // 28
// `n` and `a` no longer exist as variables, they became `name` and `age` 

You can also combine renaming with defaults in one go.

const config = { w: 800 };

const { w: width = 1024, h: height = 768 } = config;

console.log(width); // 800 = came from w 
console.log(height); // 768 = h missing, used default

Where You'll Actually Use This

The places destructuring shows up the most aren't random assignments, they're function parameters and API responses. These are worth seeing on their own.

Function parameters. You can destructure right in the parameter list. The function still receives one object, but you name the fields you care about up front. The function body never repeats the parameter name.

// Without parameter destructuring
function greet(user) {
  return `Hi ${user.name},
you're ${user.age}.`;
}

// With parameter destructuring
function greet({ name, age }) {
  return `Hi ${name},
you're ${age}.`;
}
// greet({ name: "User1", age: 28 }) = "Hi User1, you're 28."

API responses. You fetch data from a server. The response has a data field with a user inside. You need name and email. You can reach all the way in with one line.

// nested destructuring
const apiResponse = {
  status: 200,
  data: {
    user: {
      name: "User2",
      email: "user2@example.com"
    }
  }
};

// Reach three levels deep in one assignment
const { data: { user: { name, email } } } = apiResponse;

console.log(name);   // "User2"
console.log(email);  // "user2@example.com"

Deep nesting like this is fine when you know the structure. If any level might be missing (like data being null), combine it with optional chaining or check before destructuring. Nested destructuring on undefined throws an error.

What You Actually Get Out Of This

REFERENCES:

Simply JavaScript

Part 4 of 25

JavaScript is a quirky language. To master it, one should know to avoid its hidden traps along with its logic. This series showcase my journey through JS: the pain points, the breakthroughs, and the coding standards that I adopted from my mentors.

Up next

Map & Set

Leveraging Key-Value Pairs and Unique Collections in ES6+