Push and Pop are two popular methods for handling arrays in JavaScript; this short post explores both array methods.
Push
Push is used to add elements to the end of an array and returns the array’s new length. Pushing a new element into an empty array will return a value of 1 (the new length of the array).
Invoking push with no values has no effect on the original array.
let array = [1, 2]; array.push(4); // output: 3 (new length of the array) array (3) [1, 2, 4]
Push can be used to add multiple values; it has variadic arity.
array.push('a', 'b', 'c'); // output: 6 (new length of the array) array; (6) [1,2,4,'a','b','c']
Applying Push to non-Array objects
Push is generic and can be applied to mutable Array-like objects (i.e. not strings or the arguments object).
Push relies on a length property to determine where to add new entries. If length cannot be cast to a number, push will create a new length property starting from 0.
New length property creation
var obj = {}; [].push.call(obj, 1); console.log(obj); // {0: 1, length: 1}
In the code above, push created the length property and incremented it.
Casting length to a number
var obj = { length: '1' }; // '1' is a string [].push.call(obj, 1); console.log(obj); // {0: 1, length: 2}
Overwrite of the length property
var obj = { length: 'a' }; // 'a' is not coercible [].push.call(obj, 1); console.log(obj); // {0: 1, length: 1}
Pop
Pop is the inverse of Push; it removes values from the end of an array. However unlike push, pop returns the value that was popped off and not the length of the array. Pop is a nullary function: its arity is zero.
Pop invocations on empty arrays will return undefined.
Surprising asymmetry in the JavaScript language design
let popArray = [1, 2, 4]; popArray.pop(); // output: 4 (the rightmost element in the array) array (2) [1, 2]
Applying Pop to non-Array objects
Pop is generic (like push) and can be similarly applied to array-like objects.
New length property creation
var obj = {}; [].pop.call(obj); console.log(obj); // {length: 0}
In the code above, push created the length property.
Casting length to a number
var obj = { length: '1' }; // '1' is a string [].pop.call(obj); // pop console.log(obj); // { length: 0 }
Overwrite of the length property
var obj = { length: 'a', 0:'pop' }; [].pop.call(obj); // undefined console.log(obj); // {0: 'pop', length: 0}
Leave a Reply