Question
What causes different outcomes when passing an existing array versus a new array with elements from that array?
let existingArray = [1, 2, 3];
let newArray = [...existingArray];
Answer
In JavaScript, the behavior of arrays significantly depends on how they are passed to functions, which is influenced by reference versus value semantics. Understanding this can illuminate why passing an existing array can result in different outcomes than passing a newly created array with the same elements.
function modifyArray(arr) {
arr.push(4);
}
let existingArray = [1, 2, 3];
modifyArray(existingArray);
console.log(existingArray); // Output: [1, 2, 3, 4]
let newArray = [...existingArray];
modifyArray(newArray);
console.log(existingArray); // Output: [1, 2, 3, 4]
console.log(newArray); // Output: [1, 2, 3, 4]
Causes
- JavaScript passes arrays by reference, meaning that both the original array and the passed reference point to the same memory location.
- Modifying the existing array within a function will affect the original array, while modifying the new array will not affect the original since it is a copy.
Solutions
- To avoid unexpected modifications to the original array, always create a new instance by using spread operators or methods like Array.from().
- For scenarios where you want the function to only work with new copies of the array, explicitly create a new array before passing.
Common Mistakes
Mistake: Assuming that changes to the passed array do not affect the original array.
Solution: Always remember that arrays are passed by reference, hence modifications to the array will affect the original unless a copy is made.
Mistake: Not creating a new array when necessary, leading to unintended side effects.
Solution: Use methods like spread operator or Array.from() to create new instances when needed.
Helpers
- JavaScript array passing
- array reference vs value
- existing array vs new array
- JavaScript function arrays