Skip to content
How to empty an array in JavaScript?
HTML
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore
LICENSE
README.md
index.htm

README.md

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
array = []
  • Method 2
array.length = 0
  • Method 3
array.splice(0, array.length)
  • Method 4
while (array.length > 0) {
    array.pop()
}

Difference between Method 1 and the others

Method 1 only reassign a:

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:

let a = [1, 2, 3]
let b = a

// empty a and b
a.length = 0

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

Example

See index.htm

Unexpect cases: 2nd loop, arr === temp, empty temp, will empty arr.

// Unexpect
temp.splice(0, temp.length)
// Unexpect
temp.length = 0
// Unexpect
temp.splice(0, temp.length)
temp.length = 0
// Unexpect
temp.splice(0, temp.length)
temp = []
// Unexpect
temp.length = 0
temp = []

Expect cases: 2nd loop, reassign temp, won't affect arr.

// Expect
temp = []
// Expect
temp = []
temp.splice(0, temp.length)
// Expect
temp = []
temp.length = 0
You can’t perform that action at this time.