iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Destructuring

Destructuring pulls values out of arrays and objects into separate variables in one line. It reads better than ten lines of const x = obj.x.

Array destructuring

JS
const [a, b, c] = [1, 2, 3];
// a=1, b=2, c=3

// Skip with a comma
const [, second] = [1, 2];     // second = 2

// Defaults for missing values
const [x = 10, y = 20] = [1];  // x=1, y=20

// Rest collects what's left
const [first, ...others] = [1, 2, 3, 4];   // first=1, others=[2,3,4]

// Swap variables
let p = 1, q = 2;
[p, q] = [q, p];

Object destructuring

JS
const user = { name: "Ada", age: 36, role: "admin" };
const { name, role } = user;
// name = "Ada", role = "admin"

// Rename
const { name: userName } = user;     // userName = "Ada"

// Defaults
const { active = true } = user;      // active = true (not in user)

// Rest
const { name: n, ...rest } = user;   // rest = { age: 36, role: "admin" }

// Nested
const { address: { city = "?" } = {} } = user;

In function parameters

JS
function createUser({ name, role = "member" } = {}) {
  // ... uses name and role directly
}

createUser({ name: "Ada" });

// Array params
function midpoint([x1, y1], [x2, y2]) {
  return [(x1 + x2) / 2, (y1 + y2) / 2];
}
Tip: Destructuring is great for function signatures — readers can see which fields the function actually uses without scanning the body. Combine with defaults for self-documenting APIs.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Destructuring!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Pull `name` out of the user object into its own variable.

const { } = user;

Test yourself

Q1. Destructure with defaults using…
Q2. Rename while destructuring uses…
Q3. Swap two variables with…

Discussion

Loading…