kode master
kode master

Reputation: 100

Why some methods in JavaScript make a copy of the object invoked?

In JavaScript, some methods make a copy of the object that invoked it while others do not.

For example:

var numbers = [1, 2, 3, 4, 5];
numbers.map(function(x) { return x + 1 });
console.log(numbers); // [1, 2, 3, 4, 5]; 

It makes a copy of "numbers" that you have to set to another variable.

Whereas:

var numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1];

It changes the "numbers" directly. Could anyone please explain why?

Upvotes: 2

Views: 111

Answers (2)

user3382203
user3382203

Reputation: 179

This is due to the difference in time of incorporation of methods into the JavaScript.

Method reverse was there from the first version of ECMAScript.

The map was added relatively recently in the 5th version.

There is a trend to be more functional nowadays among languages. One of the main principles in functional languages is immutability of data. Therefore, these new methods of the array (namely map, filter etc) are functional and do not the change source array.

Upvotes: 2

Haroon
Haroon

Reputation: 111

The array methods in javascript is broadly classified into three - Mutator methods - Accessor methods - Iteration methods

Mutator methods - Ex : reverse(), push () etc : modify the array . As the name suggest these methods mutates the array on which they are called upon.

Accessor methods - Ex : include(), concat() etc : - do not modify the array and return some representation of the array.i.e a new array is returned which is modified array.

Iteration methods -Ex : filter(), map()- take as arguments functions to be called back while processing the array. In these methods the length of the array is already sampled/copied and the callback is performed on this arrary.

Generic methods (non-standard) - EX: join() These methods are generic in nature and is applicable to objects which “look like” Arrays.

The detailed explanation on this can be found in the below link : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

Hope this helps!!!

Upvotes: 2

Related Questions