Skip to content

Instantly share code, notes, and snippets.

@1kohei1
Created January 12, 2019 17:21
Show Gist options
  • Save 1kohei1/445f0ba754c7f0cb55e5eda420ac05b2 to your computer and use it in GitHub Desktop.
Save 1kohei1/445f0ba754c7f0cb55e5eda420ac05b2 to your computer and use it in GitHub Desktop.
function foo(x) {
x.push(4);
console.log(x); // [1,2,3,4];
x = [4,5,6];
x.push(7);
console.log(x); // [4,5,6,7]
}
var a = [1,2,3];
foo(a);
console.log(a); // [1,2,3,4];
// Here, when a is passed to foo, the reference was copied to x. At pushing 4 to x, it refers to the same array a points. However, when x is reassigned, it refers to the new array and has no impacts on a.
// To have [4,5,6,7] after calling foo, it has to directly modify the array to contain 4,5,6,7
function foo(x) {
x.length = 0;
x.push(4,5,6,7);
}
var a = [1,2,3];
foo(a);
console.log(a); // [4,5,6,7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment