I\'ve read many answers here relating to \'by value\' and \'by reference\' passing for sending arrays to javascript functions. I am however having a problem sending an array
With ES6, you can use the spread syntax and destructuring to perform a shallow copy directly in the argument list, allowing you to keep the original array unaltered.
See example below:
const arr = [1, 2, 3, 4, 5];
function timesTen([...arr]) { // [...arr] shallow copy the array
for(let i = 0; i < arr.length; i++) {
arr[i] *= 10; // this would usually change the reference
}
return arr;
}
console.log(timesTen(arr));
console.log(arr); // unaltered