javascript
examples
examples.jsā”javascript
/**
* ============================================
* 3.7 SPREAD OPERATOR - EXAMPLES
* ============================================
*/
// ============================================
// EXAMPLE 1: Copying Arrays
// ============================================
console.log('--- Copying Arrays ---');
const original = [1, 2, 3];
const copy = [...original];
console.log('Original:', original);
console.log('Copy:', copy);
console.log('Are they equal?', copy === original); // false - new array
// Modifying copy doesn't affect original
copy.push(4);
console.log('After push - Original:', original); // [1, 2, 3]
console.log('After push - Copy:', copy); // [1, 2, 3, 4]
// ============================================
// EXAMPLE 2: Concatenating Arrays
// ============================================
console.log('\n--- Concatenating Arrays ---');
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
const combined = [...arr1, ...arr2, ...arr3];
console.log('Combined:', combined); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// ============================================
// EXAMPLE 3: Adding Elements
// ============================================
console.log('\n--- Adding Elements ---');
const numbers = [2, 3, 4];
const withStart = [1, ...numbers];
console.log('With start:', withStart); // [1, 2, 3, 4]
const withEnd = [...numbers, 5];
console.log('With end:', withEnd); // [2, 3, 4, 5]
const withBoth = [0, ...numbers, 5, 6];
console.log('With both:', withBoth); // [0, 2, 3, 4, 5, 6]
// Insert in middle
const withMiddle = [...numbers.slice(0, 2), 2.5, ...numbers.slice(2)];
console.log('With middle:', withMiddle); // [2, 3, 2.5, 4]
// ============================================
// EXAMPLE 4: Spreading Strings
// ============================================
console.log('\n--- Spreading Strings ---');
const word = 'Hello';
const letters = [...word];
console.log('Letters:', letters); // ['H', 'e', 'l', 'l', 'o']
// Useful for string manipulation
const reversed = [...word].reverse().join('');
console.log('Reversed:', reversed); // 'olleH'
// ============================================
// EXAMPLE 5: Converting Iterables
// ============================================
console.log('\n--- Converting Iterables ---');
// Set to Array
const set = new Set([1, 2, 2, 3, 3, 3]);
const arrFromSet = [...set];
console.log('Array from Set:', arrFromSet); // [1, 2, 3]
// Map to Array
const map = new Map([
['a', 1],
['b', 2],
['c', 3],
]);
console.log('Map entries:', [...map]); // [['a', 1], ['b', 2], ['c', 3]]
console.log('Map keys:', [...map.keys()]); // ['a', 'b', 'c']
console.log('Map values:', [...map.values()]); // [1, 2, 3]
// ============================================
// EXAMPLE 6: Copying Objects
// ============================================
console.log('\n--- Copying Objects ---');
const person = { name: 'John', age: 30 };
const personCopy = { ...person };
console.log('Original:', person);
console.log('Copy:', personCopy);
console.log('Are they equal?', personCopy === person); // false
// Modifying copy doesn't affect original
personCopy.age = 31;
console.log('After change - Original:', person); // age: 30
console.log('After change - Copy:', personCopy); // age: 31
// ============================================
// EXAMPLE 7: Merging Objects
// ============================================
console.log('\n--- Merging Objects ---');
const defaults = {
theme: 'light',
language: 'en',
notifications: true,
};
const userPrefs = {
theme: 'dark',
fontSize: 16,
};
// User preferences override defaults
const settings = { ...defaults, ...userPrefs };
console.log('Merged settings:', settings);
// { theme: 'dark', language: 'en', notifications: true, fontSize: 16 }
// ============================================
// EXAMPLE 8: Adding/Overriding Properties
// ============================================
console.log('\n--- Adding/Overriding Properties ---');
const user = { name: 'John', age: 30 };
// Add new property
const withEmail = { ...user, email: 'john@example.com' };
console.log('With email:', withEmail);
// Override existing property
const older = { ...user, age: 31 };
console.log('Older:', older);
// Order matters!
const orderMatters = { age: 25, ...user };
console.log('Age 25 then spread:', orderMatters); // age: 30 (user.age overwrites)
// ============================================
// EXAMPLE 9: Conditional Properties
// ============================================
console.log('\n--- Conditional Properties ---');
const isAdmin = true;
const isPremium = false;
const userProfile = {
name: 'John',
...(isAdmin && { role: 'admin', permissions: ['read', 'write', 'delete'] }),
...(isPremium ? { subscription: 'premium' } : { subscription: 'free' }),
};
console.log('User profile:', userProfile);
// ============================================
// EXAMPLE 10: Function Arguments
// ============================================
console.log('\n--- Function Arguments ---');
const nums = [5, 2, 8, 1, 9];
// Without spread
console.log('Max without spread:', Math.max(nums)); // NaN
// With spread
console.log('Max with spread:', Math.max(...nums)); // 9
console.log('Min with spread:', Math.min(...nums)); // 1
// Multiple spreads in function call
const moreNums = [3, 7];
console.log('Max of both:', Math.max(...nums, ...moreNums)); // 9
// ============================================
// EXAMPLE 11: Custom Function with Spread
// ============================================
console.log('\n--- Custom Function ---');
function introduce(firstName, lastName, occupation) {
return `Hi, I'm ${firstName} ${lastName}, a ${occupation}.`;
}
const personInfo = ['John', 'Doe', 'developer'];
console.log(introduce(...personInfo));
// ============================================
// EXAMPLE 12: Array Deduplication
// ============================================
console.log('\n--- Array Deduplication ---');
const duplicates = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
const unique = [...new Set(duplicates)];
console.log('Unique values:', unique); // [1, 2, 3, 4]
// ============================================
// EXAMPLE 13: Immutable Updates
// ============================================
console.log('\n--- Immutable Updates ---');
const state = {
user: { name: 'John', age: 30 },
items: ['apple', 'banana'],
count: 2,
};
// Update nested property immutably
const newState = {
...state,
user: { ...state.user, age: 31 },
};
console.log('Original state user:', state.user);
console.log('New state user:', newState.user);
// Add to array immutably
const stateWithItem = {
...state,
items: [...state.items, 'orange'],
count: state.count + 1,
};
console.log('Original items:', state.items);
console.log('New items:', stateWithItem.items);
// ============================================
// EXAMPLE 14: Shallow Copy Warning
// ============================================
console.log('\n--- Shallow Copy Warning ---');
const nested = {
name: 'John',
address: { city: 'NYC', zip: '10001' },
};
const shallowCopy = { ...nested };
shallowCopy.name = 'Jane'; // Doesn't affect original
shallowCopy.address.city = 'LA'; // AFFECTS original!
console.log('Original name:', nested.name); // 'John'
console.log('Original city:', nested.address.city); // 'LA' - Changed!
// Solution: Deep copy nested objects too
const deeperCopy = {
...nested,
address: { ...nested.address },
};
// ============================================
// EXAMPLE 15: Excluding Properties
// ============================================
console.log('\n--- Excluding Properties ---');
const fullUser = {
id: 1,
name: 'John',
password: 'secret123',
email: 'john@example.com',
};
// Remove password using destructuring + rest
const { password, ...safeUser } = fullUser;
console.log('Safe user:', safeUser);
// { id: 1, name: 'John', email: 'john@example.com' }
console.log('\nā
All spread operator examples completed!');