I have noticed an interesting behavior when passing arrays to functions by reference. Even after modifying the array inside a function, the changes do not reflect when logging the array outside the function. For example:
let arr = [1, 2];
console.log(arr); // Logs [1, 2]
add(arr, 3)
console.log(arr); // Logs [1, 2] again
function add(array, el)
{
array = [el];
console.log(array); // Logs [3]
}
The question arises: Why does the console.log
after calling add
display [1, 2] instead of [3] (the value of the el parameter)?