Empty All Elements of Array in JavaScript

Empty All Elements of Array in JavaScript

Here giving an example, how to empty all elements of an array in JavaScript using the pop() method.

Example 1: JavaScript - Empty All Elements of Array

The following JavaScript code will remove every element of an array using the pop() method:

var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = [];

while(myArr.length){
  myNewArr.push(myArr.pop());
}

console.log(myArr, myNewArr);

Output:

0: 9
1: 8
2: 7
3: 6
4: 5
5: 4
6: 3
7: 2
8: 1
length: 9

Example 2:

let arr = [1,2,3,4,5,6,7]

let newArr = []

//console.log(arr.pop())
const fib = function(n){
   if(!n <= 0){
     newArr.push(arr.pop())
     return fib(n-1)
   }
}

fib(arr.length)

console.log(newArr)

Output:

0: 7
1: 6
2: 5
3: 4
4: 3
5: 2
6: 1
length: 7

See also: