JavaScript Destructuring
Destructuring allows you to unpack values from arrays or properties from objects into distinct variables, making data manipulation more concise and readable.
Key Topics
Array Destructuring
Extract array elements into variables by position.
let arr = ["A", "B", "C"];
let [first, second] = arr;
console.log(first, second);
Output
> A B
Explanation: The variables first and second receive "A" and "B" respectively.
Object Destructuring
Extract object properties by matching variable names to property keys.
let obj = { name: "John", age: 30 };
let { name, age } = obj;
console.log(name, age);
Output
> John 30
Explanation: Variables name and age receive corresponding values from the object.
Default Values
Set default values if properties or elements do not exist.
let [x, y = "Default"] = ["Value"];
console.log(y);
Output
> Default
Explanation: Since the second element is missing, y uses its default value "Default".
JavaScript Usage in DOM
Destructure objects returning from APIs or forms, and directly extract needed values to display on the webpage.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Destructuring in DOM</title></head>
<body>
<h1>Destructuring Demo</h1>
<button onclick="showData()">Show Data</button>
<p id="info"></p>
<script>
function showData() {
let user = { firstName: "Alice", role: "Developer" };
let { firstName, role } = user;
document.getElementById("info").textContent = firstName + " is a " + role;
}
</script>
</body>
</html>
Key Takeaways
- Arrays: Extract elements by position.
- Objects: Extract properties by key name.
- Defaults: Provide fallback values if missing.
- DOM Integration: Streamline data extraction for display in UI.