JavaScript Interview : Define DeepClone Function
In JavaScript, we have primitive types(undefined, string, number, boolean, Symbol) and reference types(object,array,function). Primitive types store in stack; memory is fixed; store the actual value while reference types store in heap; memory is not fixed; store the address of value.
Get Mchennn’s stories in your inbox
Join Medium for free to get updates from this writer.
Cope a primitive value is called deep clone and copy a primitive value is called shallow clone which means when we change the clone value we also change the original value:
// deep copy: primitive type
let a = 10
let b = a
b = 20
console.log(a) // 10
//shallow copy: reference type
let obj1 = {
name:'Alice',
age:12
}
let obj2 = obj1
obj2.age = 20
console.log(obj1.age) // 20Here is an interesting interview question:
let obj1 = {
name:'Alice',
age:12
}
let obj2 = obj1
let age = obj1.age
obj2.age = 15
age = 20
console.log(obj2.age) // 15It combines the reference types and primitive types. When we define the age, it’s a primitive type and independent from the object.
How to deep clone an object ? Here is a solution:
function DeepClone(obj={}){
if(typeof obj !== 'object' || obj === null){
// use tripple equles here is better
// since typeof null equals to 'object'
return obj
}
let result
if(obj instanceof Array){
result = []
}else{
result = {}
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
result[key] = DeepClone(obj[key])
}
}
return result
}
const obj1 = {'age' : 12}
const obj2 = DeepClone(obj1)
obj2.age = 15
console.log(obj1.age) // 12




