javascript
exercises
exercises.js⚡javascript
// ============================================
// 17.1 Destructuring - Exercises
// ============================================
// Exercise 1: Basic Array Destructuring
// Extract the first two elements from the array
const fruits = ['apple', 'banana', 'cherry', 'date'];
// Your code here:
// const [first, second] = ...
// console.log(first); // Should print: 'apple'
// console.log(second); // Should print: 'banana'
/*
Solution:
const [first, second] = fruits;
console.log(first); // 'apple'
console.log(second); // 'banana'
*/
// --------------------------------------------
// Exercise 2: Skip and Rest
// Get the first element and collect the rest, skipping the second
const numbers = [1, 2, 3, 4, 5];
// Your code here - get first and remaining (skip second):
// const [first, , ...remaining] = ...
// console.log(first); // Should print: 1
// console.log(remaining); // Should print: [3, 4, 5]
/*
Solution:
const [first, , ...remaining] = numbers;
console.log(first); // 1
console.log(remaining); // [3, 4, 5]
*/
// --------------------------------------------
// Exercise 3: Swap Variables
// Swap the values of a and b using destructuring
let a = 'hello';
let b = 'world';
// Your code here (one line):
// console.log(a); // Should print: 'world'
// console.log(b); // Should print: 'hello'
/*
Solution:
[a, b] = [b, a];
console.log(a); // 'world'
console.log(b); // 'hello'
*/
// --------------------------------------------
// Exercise 4: Object Destructuring with Rename
// Extract name as 'playerName' and score as 'playerScore'
const player = {
name: 'Alice',
score: 2500,
level: 15,
};
// Your code here:
// const { name: playerName, ... } = player;
// console.log(playerName); // Should print: 'Alice'
// console.log(playerScore); // Should print: 2500
/*
Solution:
const { name: playerName, score: playerScore } = player;
console.log(playerName); // 'Alice'
console.log(playerScore); // 2500
*/
// --------------------------------------------
// Exercise 5: Default Values
// Extract properties with defaults for missing ones
const settings = {
theme: 'dark',
fontSize: 14,
};
// Your code here - include language default 'en':
// const { theme, fontSize, language = ... } = settings;
// console.log(theme); // Should print: 'dark'
// console.log(fontSize); // Should print: 14
// console.log(language); // Should print: 'en'
/*
Solution:
const { theme, fontSize, language = 'en' } = settings;
console.log(theme); // 'dark'
console.log(fontSize); // 14
console.log(language); // 'en'
*/
// --------------------------------------------
// Exercise 6: Nested Destructuring
// Extract the city from the nested address object
const company = {
name: 'TechCorp',
address: {
street: '123 Main St',
city: 'San Francisco',
zip: '94102',
},
};
// Your code here:
// const { address: { city } } = ...
// console.log(city); // Should print: 'San Francisco'
/*
Solution:
const { address: { city } } = company;
console.log(city); // 'San Francisco'
*/
// --------------------------------------------
// Exercise 7: Deep Nested Destructuring
// Extract latitude and longitude from the nested structure
const location = {
name: 'Golden Gate Bridge',
coordinates: {
position: {
lat: 37.8199,
lng: -122.4783,
},
},
};
// Your code here:
// const { coordinates: { position: { ... } } } = location;
// console.log(lat); // Should print: 37.8199
// console.log(lng); // Should print: -122.4783
/*
Solution:
const { coordinates: { position: { lat, lng } } } = location;
console.log(lat); // 37.8199
console.log(lng); // -122.4783
*/
// --------------------------------------------
// Exercise 8: Function Parameter Destructuring
// Create a function that takes an object and destructures it
// Parameters: name, age (default 0), active (default true)
// Your code here:
// function createUser({ ... }) {
// return `${name}, age ${age}, active: ${active}`;
// }
// console.log(createUser({ name: 'Alice', age: 30 }));
// Should print: 'Alice, age 30, active: true'
// console.log(createUser({ name: 'Bob' }));
// Should print: 'Bob, age 0, active: true'
/*
Solution:
function createUser({ name, age = 0, active = true }) {
return `${name}, age ${age}, active: ${active}`;
}
console.log(createUser({ name: 'Alice', age: 30 })); // 'Alice, age 30, active: true'
console.log(createUser({ name: 'Bob' })); // 'Bob, age 0, active: true'
*/
// --------------------------------------------
// Exercise 9: Mixed Array and Object Destructuring
// Extract the first user's name and email
const response = {
status: 'success',
users: [
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' },
],
};
// Your code here:
// const { users: [{ name, email }] } = ...
// console.log(name); // Should print: 'Alice'
// console.log(email); // Should print: 'alice@example.com'
/*
Solution:
const { users: [{ name, email }] } = response;
console.log(name); // 'Alice'
console.log(email); // 'alice@example.com'
*/
// --------------------------------------------
// Exercise 10: Rest with Objects
// Extract id separately and collect everything else
const userData = {
id: 101,
username: 'alice',
email: 'alice@example.com',
role: 'admin',
active: true,
};
// Your code here:
// const { id, ...profile } = ...
// console.log(id); // Should print: 101
// console.log(profile); // Should print: { username: 'alice', email: '...', role: 'admin', active: true }
/*
Solution:
const { id, ...profile } = userData;
console.log(id); // 101
console.log(profile); // { username: 'alice', email: 'alice@example.com', role: 'admin', active: true }
*/
// --------------------------------------------
// Exercise 11: Destructuring in Loop
// Use destructuring in a for...of loop to print each person's info
const people = [
{ name: 'Alice', age: 30, city: 'NYC' },
{ name: 'Bob', age: 25, city: 'LA' },
{ name: 'Charlie', age: 35, city: 'Chicago' },
];
// Your code here:
// for (const { ... } of people) {
// console.log(`${name} (${age}) lives in ${city}`);
// }
/*
Solution:
for (const { name, age, city } of people) {
console.log(`${name} (${age}) lives in ${city}`);
}
// 'Alice (30) lives in NYC'
// 'Bob (25) lives in LA'
// 'Charlie (35) lives in Chicago'
*/
// --------------------------------------------
// Exercise 12: Return Multiple Values
// Create a function that returns min, max, and average of an array
// Then destructure the result
// Your code here:
// function getStats(arr) {
// return {
// min: ...,
// max: ...,
// avg: ...
// };
// }
// const { min, max, avg } = getStats([5, 2, 8, 1, 9, 3]);
// console.log(min, max, avg); // Should print: 1, 9, 4.67 (approximately)
/*
Solution:
function getStats(arr) {
const min = Math.min(...arr);
const max = Math.max(...arr);
const avg = arr.reduce((sum, n) => sum + n, 0) / arr.length;
return { min, max, avg };
}
const { min, max, avg } = getStats([5, 2, 8, 1, 9, 3]);
console.log(min, max, avg.toFixed(2)); // 1, 9, 4.67
*/
// --------------------------------------------
// Exercise 13: Safe Destructuring
// Safely destructure from a potentially null/undefined value
let maybeData = null;
// Your code here - should not throw error:
// const { value = 'default' } = ...
// console.log(value); // Should print: 'default'
/*
Solution:
const { value = 'default' } = maybeData || {};
console.log(value); // 'default'
// Or using nullish coalescing:
// const { value = 'default' } = maybeData ?? {};
*/
// --------------------------------------------
// Exercise 14: Complex Real-World Example
// Parse an API response and extract specific data
const apiResponse = {
status: 200,
data: {
user: {
id: 1,
profile: {
name: 'Alice',
avatar: 'alice.jpg',
},
},
posts: [
{ id: 101, title: 'First Post', likes: 42 },
{ id: 102, title: 'Second Post', likes: 17 },
],
meta: {
total: 2,
page: 1,
},
},
};
// Extract: userName, userAvatar, firstPostTitle, totalPosts
// Your code here:
/*
Solution:
const {
data: {
user: {
profile: { name: userName, avatar: userAvatar }
},
posts: [{ title: firstPostTitle }],
meta: { total: totalPosts }
}
} = apiResponse;
console.log(userName); // 'Alice'
console.log(userAvatar); // 'alice.jpg'
console.log(firstPostTitle); // 'First Post'
console.log(totalPosts); // 2
*/
// --------------------------------------------
// Exercise 15: Array Destructuring with Function Calls
// Destructure the return value of a function that returns an array
// Hint: Similar to how React's useState works
function useState(initialValue) {
let value = initialValue;
const getValue = () => value;
const setValue = (newValue) => {
value = newValue;
};
return [getValue, setValue];
}
// Your code here:
// const [getCount, setCount] = ...
// console.log(getCount()); // Should print: 0
// setCount(5);
// console.log(getCount()); // Should print: 5
/*
Solution:
const [getCount, setCount] = useState(0);
console.log(getCount()); // 0
setCount(5);
console.log(getCount()); // 5
*/