Created
September 2, 2018 07:20
-
-
Save debabrata100/301ce5a8a26ca153886cba642b40c9a3 to your computer and use it in GitHub Desktop.
It explains how shallow copy and deep copy achieved using JavaScript array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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