Reputation: 75
What is the internal code logic for Push and Pop methods in javascript..?? How does Push method stores the values in Array.
Upvotes: 0
Views: 6711
Reputation: 870
We can try some tests and test behavior:
const arr1 = []
const { push: push1 } = arr
const arr2 = []
const { push: push2 } = arr
console.log(push1 === push2) // true
console.log(push1 === Array.prototype.push) // true
push1(1) // TypeError: Cannot convert undefined or null to object
push1.call(arr1, 1) // arr1: [1], arr2: []
push2.call(arr1, 2) // arr1: [1, 2], arr2: []
push1.bind(arr2)(1) // arr1: [1, 2], arr2: [1]
push.call(arr2, 2)
And we can say that push
method uses this
under the hood...
Upvotes: 0
Reputation: 700362
The push
and pop
methods are intentionally generic, they only rely on the existance of a length
property, and that they can add and remove properties.
The push
method will read the length
property, add a property with that name, and increase the length. Basically:
function push(value) {
var len = this.length;
this[len] = value;
len++;
this.length = len;
return len;
}
The pop
method will read the length
property, decrease it, get the property with that name and remove the property. Basically:
function pop() {
var len = this.length - 1;
var value = this[len];
this.length = len;
delete this[len];
return value;
}
The actual implementations are a bit more complex, as they support for example multiple parameters for the push
method, and some more error checks. There might also implement special optimised code for when the object is actually an array, but then the generic code is still there for other objects.
The methods are intentionally generic so that they can be used on objects that aren't actually arrays. You can make your own object that supports them by just having a length
property:
var o = {
length: 0,
push: Array.prototype.push,
pop: Array.prototype.pop
};
o.push(1);
var one = o.pop();
Demo: http://jsfiddle.net/Guffa/9r4gavzb/
Upvotes: 7