- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between JavaScript deepCopy and shallowCopy
Shallow copy and deep copy are language agnostic. Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Example
let innerObj = { a: 'b', c: 'd' } let obj = { x: "test", y: innerObj } // Create a shallow copy. let copyObj = Object.assign({}, obj); // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj)
Output
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'test', c: 'd' } }
Note that shallow copies do not make clones recursively. It just does it at the top level.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection cloned.
Example
let innerObj = { a: 'b', c: 'd' } let obj = { x: "test", y: innerObj } // Create a deep copy. let copyObj = JSON.parse(JSON.stringify(obj)) // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj)
Output
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'b', c: 'd' } }
Advertisements
To Continue Learning Please Login
Login with Google