Design & Download
Your JS Library
in Seconds!!!

Snippet: Pushing & Popping from Arrays

Written by Christopher West (cwest) on December 07, 2015.
Allows pushing and popping on arrays at specific indices.
function push(array, value, opt_index) {
  opt_index == undefined ? array.push(value) : array.splice(opt_index, 0, value);
  return array;
}

function pop(array, opt_index) {
  return array.splice(opt_index == undefined ? -1 : opt_index, 1)[0];
}

push(...) API Documentation

Adds a value to an array while returning the array afterwards.

Parameters

  1. array {Array}:
    Array to add the value to.
  2. value {*}:
    The value to be added to array.
  3. opt_index {number=}:
    Optional. Defaults to array.length. The index at which value should be inserted into array. If it is less than 0 the index will be determined by counting from the end of array.

Returns

Returns array after adding value to it.

pop(...) API Documentation

Removes a value from an array while returning the array afterwards.

Parameters

  1. array {Array}:
    Array to remove a value from.
  2. opt_index {number=}:
    Optional. Defaults to array.length - 1. The index of the value in array that is to be removed. If it is less than 0 the index will be determined by counting from the end of array.

Returns

Returns array after removing a value from it.