Pointers to same array

Viewed 39

I assigned arr3 to point arr and this is true as I checked the equality. But when I changed the contents of arr by dividing all elements of arr3 by 5, arr does not seem to have reflected these changes. As I have a C++ background and a Javascript beginner can you tell me if I am doing the wrong analogy with pointers when I analyze Javascript variables? As far as understand arr3 and arr point to the same array. If one of them changes the array content, other one sees that change too but it seems this analogy does not work...

let arr = [6, 10, 14, 18];
let arr3 = arr;
console.log("arr3: " + arr3);
//arr3: 6,10,14,18
console.log(arr3 == arr);
//true

arr3 = arr.map(function (element) 
{
return element / 5;
});
console.log("arr3 after map: " + arr3);
//arr3 after map: 1.2,2,2.8,3.6
console.log("arr after arr3/5 map: " + arr);
//arr after arr3/5 map: 6,10,14,18
1 Answers

The map() function returns a new array, so arr3 is now pointing to a new array which was returned by the call to arr.map(..., while arr is still pointing the original address of the original array.

Related