javascript
exercises
exercises.js⚡javascript
/**
* ============================================
* 3.7 SPREAD OPERATOR - EXERCISES
* ============================================
*/
// ============================================
// EXERCISE 1: Copy an Array
// ============================================
/**
* Task: Create a copy of the original array using spread operator
*/
const originalArray = [1, 2, 3, 4, 5];
// Your code here:
// const copiedArray = ...
// console.log("Exercise 1:", copiedArray);
// console.log("Are they different?", copiedArray !== originalArray);
// ============================================
// EXERCISE 2: Combine Arrays
// ============================================
/**
* Task: Combine these three arrays into one using spread
*/
const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'broccoli'];
const grains = ['rice', 'wheat'];
// Your code here:
// const food = ...
// console.log("Exercise 2:", food);
// ============================================
// EXERCISE 3: Add Elements to Array
// ============================================
/**
* Task: Create new arrays by adding elements:
* 1. Add 0 at the beginning of numbers
* 2. Add 6 at the end of numbers
* 3. Add 2.5 between 2 and 3
*/
const numbers = [1, 2, 3, 4, 5];
// Your code here:
// const withZero = ...
// const withSix = ...
// const withHalf = ...
// console.log("Exercise 3:");
// console.log("With zero:", withZero);
// console.log("With six:", withSix);
// console.log("With 2.5:", withHalf);
// ============================================
// EXERCISE 4: String to Array and Back
// ============================================
/**
* Task:
* 1. Convert the string to an array of characters
* 2. Reverse the array
* 3. Join back to string
*/
const word = 'JavaScript';
// Your code here:
// const reversed = ...
// console.log("Exercise 4:", reversed); // "tpircSavaJ"
// ============================================
// EXERCISE 5: Remove Duplicates
// ============================================
/**
* Task: Remove duplicates from the array using Set and spread
*/
const withDuplicates = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
// Your code here:
// const unique = ...
// console.log("Exercise 5:", unique); // [1, 2, 3, 4]
// ============================================
// EXERCISE 6: Copy an Object
// ============================================
/**
* Task: Create a copy of the user object using spread
*/
const originalUser = { name: 'Alice', age: 25 };
// Your code here:
// const userCopy = ...
// console.log("Exercise 6:", userCopy);
// console.log("Are they different?", userCopy !== originalUser);
// ============================================
// EXERCISE 7: Merge Objects
// ============================================
/**
* Task: Merge defaults with userSettings
* userSettings should override defaults
*/
const defaults = { theme: 'light', fontSize: 14, showSidebar: true };
const userSettings = { theme: 'dark', fontSize: 18 };
// Your code here:
// const finalSettings = ...
// console.log("Exercise 7:", finalSettings);
// ============================================
// EXERCISE 8: Add Property to Object
// ============================================
/**
* Task: Create a new object with all product properties plus a 'discount' property
*/
const product = { name: 'Laptop', price: 1000, category: 'Electronics' };
const discountPercent = 10;
// Your code here:
// const productWithDiscount = ...
// console.log("Exercise 8:", productWithDiscount);
// ============================================
// EXERCISE 9: Override Property
// ============================================
/**
* Task: Create a new config object where debug is set to true
* while keeping all other properties the same
*/
const config = { debug: false, logLevel: 'error', maxRetries: 3 };
// Your code here:
// const devConfig = ...
// console.log("Exercise 9:", devConfig);
// ============================================
// EXERCISE 10: Conditional Properties
// ============================================
/**
* Task: Create an order object that includes:
* - All base order properties
* - 'express' property only if isExpress is true
* - 'giftWrap' property only if isGift is true
*/
const baseOrder = { items: ['item1', 'item2'], total: 50 };
const isExpress = true;
const isGift = false;
// Your code here:
// const order = ...
// console.log("Exercise 10:", order);
// ============================================
// EXERCISE 11: Use Spread with Math Functions
// ============================================
/**
* Task: Find the max, min, and calculate the sum of the scores
* Use spread operator with Math.max and Math.min
*/
const scores = [85, 92, 78, 96, 88];
// Your code here:
// const maxScore = ...
// const minScore = ...
// const sum = ...(hint: use reduce)
// console.log("Exercise 11:");
// console.log("Max:", maxScore);
// console.log("Min:", minScore);
// console.log("Sum:", sum);
// ============================================
// EXERCISE 12: Call Function with Spread
// ============================================
/**
* Task: Use spread to pass the date parts to the function
*/
function formatDate(year, month, day) {
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(
2,
'0'
)}`;
}
const dateParts = [2024, 3, 15];
// Your code here:
// const formattedDate = ...
// console.log("Exercise 12:", formattedDate); // "2024-03-15"
// ============================================
// EXERCISE 13: Immutable Array Update
// ============================================
/**
* Task: Create a new todos array where the second todo is marked as completed
* without mutating the original array
*/
const todos = [
{ id: 1, text: 'Learn JS', completed: true },
{ id: 2, text: 'Learn React', completed: false },
{ id: 3, text: 'Build project', completed: false },
];
// Your code here:
// const updatedTodos = ...
// console.log("Exercise 13:");
// console.log("Original:", todos[1].completed); // false
// console.log("Updated:", updatedTodos[1].completed); // true
// ============================================
// EXERCISE 14: Remove Property from Object
// ============================================
/**
* Task: Create a new object without the 'password' property
* using destructuring and spread
*/
const userWithPassword = {
id: 1,
username: 'john_doe',
email: 'john@example.com',
password: 'secret123',
};
// Your code here:
// const { ..., ...publicUser } = userWithPassword;
// console.log("Exercise 14:", publicUser);
// ============================================
// BONUS: Deep Merge
// ============================================
/**
* Task: Create a properly merged settings object where
* nested objects are also merged (not replaced)
*
* Expected result:
* {
* theme: { primary: 'blue', secondary: 'gray', accent: 'yellow' },
* layout: { sidebar: true, header: true }
* }
*/
const baseSettings = {
theme: { primary: 'blue', secondary: 'gray' },
layout: { sidebar: true },
};
const overrides = {
theme: { accent: 'yellow' },
layout: { header: true },
};
// Your code here:
// const mergedSettings = ...
// console.log("Bonus:", mergedSettings);
// ============================================
// SOLUTIONS
// ============================================
/**
* Exercise 1:
* const copiedArray = [...originalArray];
*
* Exercise 2:
* const food = [...fruits, ...vegetables, ...grains];
*
* Exercise 3:
* const withZero = [0, ...numbers];
* const withSix = [...numbers, 6];
* const withHalf = [...numbers.slice(0, 2), 2.5, ...numbers.slice(2)];
*
* Exercise 4:
* const reversed = [...word].reverse().join('');
*
* Exercise 5:
* const unique = [...new Set(withDuplicates)];
*
* Exercise 6:
* const userCopy = { ...originalUser };
*
* Exercise 7:
* const finalSettings = { ...defaults, ...userSettings };
*
* Exercise 8:
* const productWithDiscount = { ...product, discount: discountPercent };
*
* Exercise 9:
* const devConfig = { ...config, debug: true };
*
* Exercise 10:
* const order = {
* ...baseOrder,
* ...(isExpress && { express: true }),
* ...(isGift && { giftWrap: true })
* };
*
* Exercise 11:
* const maxScore = Math.max(...scores);
* const minScore = Math.min(...scores);
* const sum = scores.reduce((a, b) => a + b, 0);
*
* Exercise 12:
* const formattedDate = formatDate(...dateParts);
*
* Exercise 13:
* const updatedTodos = todos.map((todo, index) =>
* index === 1 ? { ...todo, completed: true } : todo
* );
*
* Exercise 14:
* const { password, ...publicUser } = userWithPassword;
*
* Bonus:
* const mergedSettings = {
* theme: { ...baseSettings.theme, ...overrides.theme },
* layout: { ...baseSettings.layout, ...overrides.layout }
* };
*/