Global Trend Radar
Dev.to US tech 2026-06-26 09:00

JavaScriptにおける分割代入

原題: Destructuring in JavaScript

元記事を開く →

分析結果

カテゴリ
不動産
重要度
55
トレンドスコア
17
要約
JavaScriptの分割代入は、配列やオブジェクトから値を簡単に取り出すための構文です。これにより、変数の宣言と代入を同時に行うことができ、コードがより簡潔で読みやすくなります。配列の場合、インデックスを指定して要素を取得し、オブジェクトの場合はプロパティ名を指定して値を取得します。分割代入は、関数の引数やデフォルト値の設定にも利用され、柔軟なコーディングを可能にします。
キーワード
"Destructuring is JavaScript's way of letting you unpack what you need and leave the rest behind." Introduction You've worked with arrays and objects in JavaScript. You know how to access their values. But have you noticed how repetitive it gets? const user = { name : " Alice " , age : 28 , city : " Delhi " }; const name = user . name ; const age = user . age ; const city = user . city ; Three lines. Three times you wrote user.something . Now imagine doing this for an object with ten properties. Or doing it across dozens of files. Destructuring is JavaScript's answer to that repetition. It's a concise syntax that lets you extract values from arrays and objects directly into variables — in a single line. No dot notation chains. No index lookups. Just clean, readable assignments. 1. What Does Destructuring Mean? Destructuring means pulling values out of a data structure and binding them to named variables , using a syntax that mirrors the shape of the data itself. The key insight: instead of describing where to put things (left side) and then going to fetch them (right side), destructuring lets you describe the shape of what you expect on the left — and JavaScript fills in the values from the right. // Traditional access — fetch and assign one by one const name = user . name ; const age = user . age ; // Destructuring — describe the shape, get the values const { name , age } = user ; Both do the same thing. The destructured version is just less noise. Destructuring works on two kinds of data structures in JavaScript: objects and arrays . The syntax is slightly different for each, and for good reason. 2. Destructuring Arrays Array destructuring uses square brackets [] on the left side of the assignment. Values are extracted by position — the first variable gets index 0 , the second gets index 1 , and so on. Before vs. After const colors = [ " red " , " green " , " blue " ]; // ❌ Before — manual index access const first = colors [ 0 ]; const second = colors [ 1 ]; const third = colors [ 2 ]; // ✅ After — array destructuring const [ first , second , third ] = colors ; ARRAY DESTRUCTURING — POSITIONAL MAPPING colors → [ "red", "green", "blue" ] ↓ ↓ ↓ [first, second, third ] first = "red" second = "green" third = "blue" Skipping Elements You're not forced to take every value. Leave a gap with a comma to skip positions you don't need. const scores = [ 95 , 82 , 76 , 61 , 54 ]; // Only want first and third — skip the second const [ gold , , bronze ] = scores ; console . log ( gold ); // 95 console . log ( bronze ); // 76 The Rest Element Capture the remaining items into a new array using the rest syntax ( ... ). const [ top , ... rest ] = [ 1 , 2 , 3 , 4 , 5 ]; console . log ( top ); // 1 console . log ( rest ); // [2, 3, 4, 5] Swapping Variables One elegant trick array destructuring unlocks — swapping two variables without a temporary placeholder: let a = 1 ; let b = 2 ; // ❌ Before — needs a temp variable let temp = a ; a = b ; b = temp ; // ✅ After — one-line swap [ a , b ] = [ b , a ]; console . log ( a ); // 2 console . log ( b ); // 1 3. Destructuring Objects Object destructuring uses curly braces {} on the left side. Unlike arrays, values are matched by property name — not by position — so the order on the left doesn't matter. Before vs. After const product = { id : 101 , name : " Mechanical Keyboard " , price : 4999 , inStock : true }; // ❌ Before — repeated property lookups const id = product . id ; const name = product . name ; const price = product . price ; const inStock = product . inStock ; // ✅ After — object destructuring const { id , name , price , inStock } = product ; OBJECT DESTRUCTURING — NAME - BASED EXTRACTION product = { id : 101 , ──► const id = 101 name : " Keyboard " , ──► const name = " Keyboard " price : 4999 , ──► const price = 4999 inStock : true ──► const inStock = true } { id , name , price , inStock } = product ↑ Matches by property name — order doesn ' t matter Renaming Variables Sometimes the property name from the object clashes with an existing variable, or just isn't descriptive enough in context. Use a colon : to rename while destructuring. const response = { status : 200 , data : { user : " Alice " } }; // Rename 'status' → 'statusCode', 'data' → 'payload' const { status : statusCode , data : payload } = response ; console . log ( statusCode ); // 200 console . log ( payload ); // { user: "Alice" } // Original names (status, data) no longer exist as variables Nested Object Destructuring Objects inside objects can be destructured in one go by mirroring the nested shape. const user = { name : " Akash " , address : { city : " Patna " , pincode : " 800001 " } }; // ❌ Before — two-step access const city = user . address . city ; const pincode = user . address . pincode ; // ✅ After — nested destructuring const { name , address : { city , pincode } } = user ; console . log ( name ); // "Akash" console . log ( city ); // "Patna" console . log ( pincode ); // "800001" Note that address itself is not created as a variable here — it's only used as a path to reach city and pincode . Destructuring in Function Parameters This is one of the most common places you'll see object destructuring in real code. Instead of passing a full object and accessing its properties inside the function, you destructure right in the parameter list. const order = { id : 42 , item : " Laptop " , quantity : 2 }; // ❌ Before — access properties inside the function function printOrder ( order ) { console . log ( `Order # ${ order . id } : ${ order . quantity } x ${ order . item } ` ); } // ✅ After — destructure in the parameter itself function printOrder ({ id , item , quantity }) { console . log ( `Order # ${ id } : ${ quantity } x ${ item } ` ); } printOrder ( order ); // Order #42: 2x Laptop 4. Default Values What happens when you destructure a property that doesn't exist? You get undefined . Default values let you specify a fallback for exactly that case. Default Values in Object Destructuring const settings = { theme : " dark " }; // 'language' doesn't exist in settings const { theme , language } = settings ; console . log ( language ); // undefined ← not great // With a default value const { theme , language = " en " } = settings ; console . log ( language ); // "en" ← much better The default only kicks in when the value is undefined — not when it's null , 0 , or "" . const config = { timeout : 0 , retries : null }; const { timeout = 5000 , retries = 3 , debug = false } = config ; console . log ( timeout ); // 0 ← 0 is a real value, default ignored console . log ( retries ); // null ← null is a real value, default ignored console . log ( debug ); // false ← undefined, so default applies Default Values in Array Destructuring const [ primary = " blue " , secondary = " gray " ] = [ " red " ]; console . log ( primary ); // "red" ← value present, default ignored console . log ( secondary ); // "gray" ← nothing at index 1, default applies Combining Rename and Default You can rename and set a default at the same time: const user = {}; // Rename 'name' → 'username', with fallback "Guest" const { name : username = " Guest " } = user ; console . log ( username ); // "Guest" 5. Benefits of Destructuring Destructuring is more than a shorthand — it changes how you think about working with data. Less Repetition // ❌ Without destructuring — object name repeated everywhere function formatAddress ( location ) { return ` ${ location . street } , ${ location . city } , ${ location . state } ${ location . zip } ` ; } // ✅ With destructuring — clean and flat function formatAddress ({ street , city , state , zip }) { return ` ${ street } , ${ city } , ${ state } ${ zip } ` ; } Cleaner API Responses Real-world API responses are often deeply nested. Destructuring lets you pull out exactly what you need without intermediate variables: // A typical API response const response = { status : 200 , data : { user : { id : 7 , name : " Akash " , email : " [email protected] " , role : " admin " } } }; // Extract only what this function cares about const { data : { user : { name , role } } } = response ; console . log ( name ); // "Akash" console . log ( role ); // "admin" Readable Function Return Values Destructuring makes functions that return multiple values feel natural: function getMinMax ( numbers ) { return { min : Math . min (... numbers ), max : Math . max (... numbers ) }; } // Named return values — no [0] and [1] guessing const { min , max } = getMinMax ([ 3 , 1 , 9 , 4 , 7 ]); console . log ( min ); // 1 console . log ( max ); // 9 Works Beautifully with Loops const users = [ { id : 1 , name : " Alice " , role : " admin " }, { id : 2 , name : " Bob " , role : " viewer " }, { id : 3 , name : " Carol " , role : " editor " } ]; // Destructure each object directly in the loop for ( const { name , role } of users ) { console . log ( ` ${ name } is a ${ role } ` ); } // Alice is a admin // Bob is a viewer // Carol is a editor Before vs. After: A Full Comparison WITHOUT DESTRUCTURING │ WITH DESTRUCTURING ─────────────────────────────────────┼─────────────────────────────────────── const name = user . name ; │ const { const age = user . age ; │ name , const city = user . city ; │ age , const country = user . country ; │ city , │ country │ } = user ; ─────────────────────────────────────┼─────────────────────────────────────── const r = rgb [ 0 ]; │ const [ r , g , b ] = rgb ; const g = rgb [ 1 ]; │ const b = rgb [ 2 ]; │ ─────────────────────────────────────┼─────────────────────────────────────── function greet ( user ) { │ function greet ({ name , age = 0 }) { const name = user . name ; │ console . log ( `Hi ${ name } , ${ age } ` ); const age = user . age || 0 ; │ } console . log ( `Hi ${ name } , ${ age } ` ); │ } │ ─────────────────────────────────────┼─────────────────────────────────────── ❌ Repetitive property access │ ✅ Clean , intention - revealing syntax ❌ More lines for same result │ ✅ Fewer lines , same result ❌ Easy to misty