100 of 264 menu

pop method

The pop method removes the last element from an array. In this case, the original array is modified, and the removed element is returned as the result of the method.

Syntax

array.pop();

Example

Let's remove the last element from an array:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.pop(); console.log(arr);

The code execution result:

['a', 'b', 'c', 'd']

Example

Let's output the last element that was removed from an original array:

let arr = ['a', 'b', 'c', 'd', 'e']; let del = arr.pop(); console.log(del);

The code execution result:

'e'

Example . Usage

Let's convert an array into the string '16-25-34'. To solve the problem, we use a combination of pop, shift, push and join methods:

let arr = ['1', '2', '3', '4', '5', '6']; let res = []; while (arr.length > 0) { // array is reduced in a loop until it reaches zero let first = arr.shift(); let last = arr.pop(); let str = first + last; // there will be the string '16', then '25', then '34' res.push(str); } // After the loop, res contains the array ['16', '25', '34']. We merge it into a string: res = res.join('-'); console.log(res);

The code execution result:

'16-25-34'

See also

  • the shift method
    that removes the first element of an array
  • the push and unshift methods
    that add elements to an array
  • the join method
    that concatenates the array elements into a string by specified separator
byenru