In JavaScript , I am using Array method 'map' and observed that it is modifying the array on which it is called. But the documentation I read it should NOT be the case?
"Note that map() returns a new array: it does not modify the array it is invoked on" - JavaScript - The definitive Guide 6th Edition.
var arr = [{x:1},{y:2},{z:3}]
var arr1 = arr.map(function(obj) {
for (var prp in obj) {
obj[prp] *= obj[prp];
}
return obj;
})
// function to print the array
printArray = function(arr) {
for (var i = 0; i < arr.length; i++) {
for (prp in arr[i]) {
console.log(prp, arr[i][prp])
}
}
}
Output
printArray(arr1)
x 1
y 4
z 9
printArray(arr)
x 1
y 4
z 9
As we can see the original array 'arr' is also modified?