AI News Hub Logo

AI News Hub

Destructuring in JavaScript

DEV Community
Pratham

Unpack values from arrays and objects into neat, individual variables — in a single line. Here's a pattern I used to write all the time before I learned about destructuring: const user = { name: "Pratham", age: 22, city: "Delhi", }; const name = user.name; const age = user.age; const city = user.city; console.log(name); // "Pratham" console.log(age); // 22 console.log(city); // "Delhi" Three lines just to pull values out of an object and assign them to variables. It works, but it's repetitive. You're typing user. three times, and if the object had 10 properties, you'd have 10 lines of essentially the same pattern. Destructuring lets you do all of that in one line: const { name, age, city } = user; Same result. One line. No repetition. When I first saw this in the ChaiCode Web Dev Cohort 2026, it felt like a cheat code. Let me show you how it works. Destructuring is a JavaScript syntax that lets you extract values from arrays or objects and assign them to variables — all in a single, clean statement. Think of it like unpacking a suitcase. Instead of reaching in and pulling out items one at a time: Suitcase → reach in → grab shirt → put on shelf Suitcase → reach in → grab pants → put on shelf Suitcase → reach in → grab shoes → put on shelf You dump everything out at once and each item goes to its labeled spot: Suitcase → { shirt, pants, shoes } → all on their shelves instantly That's destructuring. One operation, multiple variables created. Object destructuring is the one you'll use most often. It lets you pull out specific properties by name. const { property1, property2, property3 } = object; The variable names inside { } must match the property names in the object. const student = { name: "Pratham", age: 22, course: "Web Dev Cohort 2026", }; // Without destructuring const name = student.name; const age = student.age; const course = student.course; // With destructuring — same result, one line const { name, age, course } = student; console.log(name); // "Pratham" console.log(age); // 22 console.log(course); // "Web Dev Cohort 2026" const student = { name: "Pratham", ──→ const name = "Pratham" age: 22, ──→ const age = 22 course: "Web Dev 2026" ──→ const course = "Web Dev 2026" }; ⬇ Destructuring does this in ONE step ⬇ const { name, age, course } = student; ↑ ↑ ↑ │ │ └── matches key "course" → gets "Web Dev 2026" │ └── matches key "age" → gets 22 └── matches key "name" → gets "Pratham" You can pick only the properties you need. The rest are simply ignored. const product = { title: "Laptop", price: 75000, brand: "Dell", inStock: true, }; // I only need title and price const { title, price } = product; console.log(title); // "Laptop" console.log(price); // 75000 // brand and inStock are still in the object, just not extracted What if the property name conflicts with an existing variable, or you just want a different name? Use the : syntax: const person = { name: "Pratham", age: 22, }; // Rename 'name' to 'userName' and 'age' to 'userAge' const { name: userName, age: userAge } = person; console.log(userName); // "Pratham" console.log(userAge); // 22 // console.log(name); // ❌ ReferenceError — 'name' wasn't created, 'userName' was The syntax reads as: "take the property name and store it as userName." Objects inside objects? You can destructure those too: const user = { name: "Pratham", address: { city: "Delhi", state: "Delhi", pin: 110001, }, }; const { name, address: { city, pin }, } = user; console.log(name); // "Pratham" console.log(city); // "Delhi" console.log(pin); // 110001 Array destructuring works by position instead of by name. The first variable gets the first element, the second gets the second, and so on. const [var1, var2, var3] = array; const colors = ["red", "green", "blue"]; // Without destructuring const first = colors[0]; const second = colors[1]; const third = colors[2]; // With destructuring const [first, second, third] = colors; console.log(first); // "red" console.log(second); // "green" console.log(third); // "blue" const colors = ["red", "green", "blue"]; ↓ ↓ ↓ const [first, second, third] = colors; ↓ ↓ ↓ "red" "green" "blue" Position 0 → first = "red" Position 1 → second = "green" Position 2 → third = "blue" Don't need the second element? Just leave an empty slot with a comma: const scores = [95, 82, 78, 90]; const [best, , , fourth] = scores; // ↑ ↑ // skipped positions console.log(best); // 95 console.log(fourth); // 90 One of the coolest tricks with array destructuring — swapping two variables without a temporary variable: let a = 1; let b = 2; // Traditional swap (needs a temp variable) // let temp = a; // a = b; // b = temp; // Destructuring swap — one line, no temp [a, b] = [b, a]; console.log(a); // 2 console.log(b); // 1 ...rest) Want to grab the first couple of elements and dump the rest into another array? const numbers = [1, 2, 3, 4, 5, 6]; const [first, second, ...remaining] = numbers; console.log(first); // 1 console.log(second); // 2 console.log(remaining); // [3, 4, 5, 6] The ...remaining collects everything that's left into a new array. This works with objects too: const user = { name: "Pratham", age: 22, city: "Delhi", course: "Web Dev", }; const { name, ...otherDetails } = user; console.log(name); // "Pratham" console.log(otherDetails); // { age: 22, city: "Delhi", course: "Web Dev" } What happens if the property or element you're trying to destructure doesn't exist? You get undefined. Default values let you set a fallback. const settings = { theme: "dark", language: "en", }; const { theme, language, fontSize = 16 } = settings; console.log(theme); // "dark" console.log(language); // "en" console.log(fontSize); // 16 — not in the object, so the default kicks in If fontSize existed in settings, its actual value would be used. The default only applies when the value is undefined. const rgb = [255, 100]; const [red, green, blue = 0] = rgb; console.log(red); // 255 console.log(green); // 100 console.log(blue); // 0 — no third element, default is used const config = { apiUrl: "https://api.example.com", }; const { apiUrl: url, timeout: requestTimeout = 5000 } = config; console.log(url); // "https://api.example.com" console.log(requestTimeout); // 5000 This reads as: "take apiUrl and call it url; take timeout and call it requestTimeout, but if it doesn't exist, default to 5000." Let's see the transformation across different scenarios: // ❌ Before const name = person.name; const age = person.age; const city = person.city; // ✅ After const { name, age, city } = person; // ❌ Before const first = scores[0]; const second = scores[1]; const third = scores[2]; // ✅ After const [first, second, third] = scores; // ❌ Before function displayUser(user) { console.log(user.name); console.log(user.age); console.log(user.city); } // ✅ After — destructure right in the parameter function displayUser({ name, age, city }) { console.log(name); console.log(age); console.log(city); } displayUser({ name: "Pratham", age: 22, city: "Delhi" }); This last one — destructuring in function parameters — is incredibly common in modern JavaScript and React. You'll see it everywhere. Let's summarize why destructuring isn't just a "nice to have" but a genuine improvement: Benefit Explanation Less repetition No more obj.property over and over Cleaner code One line instead of many for extracting values Better readability You instantly see which properties are being used Default values Handle missing data gracefully without extra if checks Function params Destructure right in the parameter list — cleaner function signatures Modern standard Used everywhere in ES6+, React, Node.js, and APIs const movie = { title: "Inception", director: "Christopher Nolan", year: 2010, rating: 8.8, }; // Destructure title and director const { title, director } = movie; console.log(`${title} by ${director}`); // "Inception by Christopher Nolan" const topCities = ["Tokyo", "Delhi", "Shanghai", "São Paulo", "Mumbai"]; const [first, second, ...others] = topCities; console.log(`#1: ${first}`); // "#1: Tokyo" console.log(`#2: ${second}`); // "#2: Delhi" console.log(`Others:`, others); // Others: ["Shanghai", "São Paulo", "Mumbai"] const userProfile = { username: "pratham16", email: "[email protected]", }; const { username, email, bio = "No bio yet." } = userProfile; console.log(username); // "pratham16" console.log(bio); // "No bio yet." const printStudent = ({ name, age, course }) => { console.log(`${name}, ${age} — enrolled in ${course}`); }; printStudent({ name: "Pratham", age: 22, course: "Web Dev Cohort 2026", }); // "Pratham, 22 — enrolled in Web Dev Cohort 2026" let x = 100; let y = 200; console.log(`Before: x=${x}, y=${y}`); // Before: x=100, y=200 [x, y] = [y, x]; console.log(`After: x=${x}, y=${y}`); // After: x=200, y=100 Destructuring extracts values from objects (by key name) and arrays (by position) into individual variables — all in one line. Object destructuring uses { } and matches variable names to property names. You can rename with : and skip properties you don't need. Array destructuring uses [ ] and matches by position. You can skip elements with commas and collect leftovers with ...rest. Default values (= fallback) kick in when a property or element is undefined. They're perfect for handling missing data. Destructuring is the modern standard — you'll see it in function parameters, API responses, React props, and virtually all modern JavaScript code. Destructuring is one of those ES6 features that fundamentally changes how you write JavaScript. Before it, extracting values was tedious and repetitive. After it, your code becomes tighter, more readable, and more expressive. And the best part? Once you start using it, it becomes second nature — you'll destructure without even thinking about it. I'm working through all of this in the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and destructuring comes up in nearly every lesson now. Array methods, React components, API responses — it's everywhere. Getting comfortable with it early is one of the best investments you can make. Connect with me on LinkedIn or visit PrathamDEV.in to follow along. More articles on the way as the learning continues. Happy coding! 🚀 Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode