There are several ways to empty a JavaScript array, but they are not equivalent. Use array.length = 0 when you want to clear the existing array object; use array = [] when you only need to reassign that variable to a new empty array.
const scripts = ["PHP", "JavaScript", "Python"];
scripts.length = 0;
console.log(scripts); // []
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
scripts.length = 0;
console.log(scripts); // []
This mutates the array object itself, so all references to that same array see it become empty.
let scripts = ["PHP", "JavaScript", "Python"];
scripts = [];
console.log(scripts); // []
This does not clear the old array object. It simply makes the variable refer to a new array.
let scripts = ["PHP", "JavaScript"];
const alias = scripts;
scripts = [];
console.log(scripts); // []
console.log(alias); // ["PHP", "JavaScript"]
Compare with length = 0:
const scripts = ["PHP", "JavaScript"];
const alias = scripts;
scripts.length = 0;
console.log(alias); // []
This distinction is the most important reason to choose one emptying technique over another.
const scripts = ["PHP", "JavaScript", "Python"];
const removed = scripts.splice(0);
console.log(scripts); // []
console.log(removed); // ["PHP", "JavaScript", "Python"]
splice(0) mutates the existing array and also returns an array containing the removed elements. Use it when those removed values are useful; otherwise length = 0 is simpler.
const scripts = ["PHP", "JavaScript", "Python"];
while (scripts.length > 0) {
const removed = scripts.pop();
console.log("Removed:", removed);
}
This is appropriate only when you need to process each removed value. It is unnecessarily verbose if the goal is simply to clear the array.
Yes. const prevents reassignment of the variable, but the array object can still be mutated.
const scripts = ["PHP", "JavaScript"];
scripts.length = 0; // allowed
// scripts = []; // TypeError: assignment to constant variable
| Method | Mutates same array? | Other references see empty array? | Best use |
|---|---|---|---|
array.length = 0 | Yes | Yes | Clear existing array object simply |
array = [] | No; reassigns variable | No | Discard this variable's reference |
array.splice(0) | Yes | Yes | Clear and capture removed elements |
Repeated pop() | Yes | Yes | Process values while removing them |
array = [] empties the object referenced elsewhere.const variable to [].delete array[index] to clear items; delete can leave empty slots and does not reduce length.length = 0 directly expresses the goal.Array length Property Remove from End with pop() Remove by Position with splice()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.