How to empty an array in JavaScript?

When I write pathfinding codes in JavaScript, I ran into this problem: how to empty the array?

Methods

  • Method 1

1
array = []

  • Method 2

1
array.length = 0

  • Method 3

1
array.splice(0, array.length)

  • Method 4

1
2
3
while (array.length > 0) {
array.pop()
}

Difference between Method 1 and the others

Method 1 only reassign a:

1
2
3
4
5
6
7
8
let a = [1, 2, 3]
let b = a

// empty a, but doesn't affect b
a = []

console.log('a =', a)
console.log('b =', b)

Method 2, 3, 4, will empty multiple variables referencing the same object:

1
2
3
4
5
6
7
8
let a = [1, 2, 3]
let b = a

// empty a and b
a.length = 0

console.log('a =', a)
console.log('b =', b)

More

See https://github.com/UMU618/js-empty-array#example