Skip to content

Instantly share code, notes, and snippets.

@jitendra19
Created January 30, 2019 14:39
Show Gist options
  • Save jitendra19/82eb3c05a1e2a1d6f203f108e46488a6 to your computer and use it in GitHub Desktop.
Save jitendra19/82eb3c05a1e2a1d6f203f108e46488a6 to your computer and use it in GitHub Desktop.
// What would be the output of following code?
var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"}];
var arrB = arrA.slice();
arrB[0].prop1=42;
console.log(arrA);
// The output will be [{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5].
// The slice function copies all the elements of the array returning the new array. However, it doesn't do deep copying. Instead it does shallow copying. You can imagine slice implemented like this:
// function slice(arr) {
// var result = [];
// for (i = 0; i< arr.length; i++) {
// result.push(arr[i]);
// }
// return result;
// }
// Look at the line with result.push(arr[i]).
// If arr[i] happens to be a number or string, it will be passed by value, in other words, copied.
// If arr[i] is an object, it will be passed by reference.
// In case of our array arr[0] is an object {prop1: "value of array A!!"}.
// Only the reference to this object will be copied.
// This effectively means that arrays arrA and arrB share first two elements.
// This is why changing the property of arrB[0] in arrB will also change the arrA[0].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment