Skip to content

Instantly share code, notes, and snippets.

@debabrata100
Created September 2, 2018 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debabrata100/301ce5a8a26ca153886cba642b40c9a3 to your computer and use it in GitHub Desktop.
Save debabrata100/301ce5a8a26ca153886cba642b40c9a3 to your computer and use it in GitHub Desktop.
It explains how shallow copy and deep copy achieved using JavaScript array
const a = [true,false,undefined,null,NaN,"array",5];
console.log('---------Original Array-----------');
console.log(a); // [ true, false, undefined, null, NaN, 'array', 5 ]
/*-------Shalow copy-----------*/
console.log('---------Shalow Copying-----------');
//slice
console.log('---------Shalow Copying with slice()-----------');
const b = a.slice();
console.log(b); // [ true, false, undefined, null, NaN, 'array', 5 ]
//spread operator
console.log('---------Shalow Copying with spread operator-----------');
const c = [...a];
console.log(c,a); // // [ true, false, undefined, null, NaN, 'array', 5 ]
/*---------Deep Copying-----------*/
console.log('---------Trying Deep Copying using slice-----------');
const aa = [['deep copy']];
const bb = aa.slice();
bb[0].push('new element');
console.log(aa,bb); // [ [ 'deep copy', 'new element' ] ] [ [ 'deep copy', 'new element' ] ]
console.log('---------Deep Copying-----------');
const dd = [['deep copy - 1']]
console.log('---------Original Array-----------');
console.log(dd);
console.log('---------Deep Copying with JSON.parse(JSON.stringify())-----------');
const deepCopy = JSON.parse(JSON.stringify(dd));
deepCopy[0].push('deep copy -2');
console.log(dd,deepCopy); // [ [ 'deep copy - 1' ] ] [ [ 'deep copy - 1', 'deep copy -2' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment