Skip to content

Instantly share code, notes, and snippets.

@lusan
Created July 5, 2019 13:54
Show Gist options
  • Save lusan/55b907ab5c47c4059a16ce7f522802c3 to your computer and use it in GitHub Desktop.
Save lusan/55b907ab5c47c4059a16ce7f522802c3 to your computer and use it in GitHub Desktop.
Deep clone object polyfill
function deepClone(object){
var newObject = {};
for(var key in object){
if(typeof object[key] === 'object' && object[key] !== null ){
newObject[key] = deepClone(object[key]);
}else{
newObject[key] = object[key];
}
}
return newObject;
}
@shihabus
Copy link

shihabus commented Apr 7, 2020

In line 4 we also need to check for Array.

typeof [] and typeof {} are the same, which is object

@the-fejw
Copy link

the-fejw commented Nov 7, 2021

let's say if object[key] is a function type, then newObject[key] is still pointing to the original object[key] instead of clone to a new memory space

@kSharma-rediker
Copy link

it will not work for function, array values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment