Skip to content

Instantly share code, notes, and snippets.

@siddharth-sunchu
Last active June 26, 2021 23:15
Show Gist options
  • Save siddharth-sunchu/9ad25ef7e7eb98659b4a8bf9d7d761fe to your computer and use it in GitHub Desktop.
Save siddharth-sunchu/9ad25ef7e7eb98659b4a8bf9d7d761fe to your computer and use it in GitHub Desktop.
const employee = {
name: 'Siddharth',
age: 30,
salary: {
annual: '100K',
hourly: '$50'
}
};
const copyOfEmployee = {...employee, salary: { ...employee.salary }}; // => DEEP COPY
console.log('employee => ', employee);
console.log('copyOfEmployee => ', copyOfEmployee);
/*
employee => {
name: 'Siddharth',
age: 35,
salary: { annual: '100K', hourly: '$50' }
}
copyOfEmployee => {
name: 'Siddharth',
age: 35,
salary: { annual: '100K', hourly: '$50' }
}
*/
console.log('------------After Modification-----------');
copyOfEmployee.name = 'Elon Musk';
copyOfEmployee.salary.annual = '120K';
console.log('employee => ', employee);
console.log('copyOfEmployee => ', copyOfEmployee);
/*
------------After Modification-----------
employee => {
name: 'Siddharth',
age: 30,
salary: { annual: '100K', hourly: '$50' }
}
copyOfEmployee => {
name: 'Elon Musk',
age: 30,
salary: { annual: '120K', hourly: '$50' }
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment