WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Empty an Array in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the length Property

You can simply use the array's length property to empty an array in JavaScript.

Let's take a look at an example to understand how it basically works:

var arr1 = [1,2,3,4,5];

// Reference arr1 by another variable
var arr2 = arr1;

// Making arr1 empty
arr1.length = 0;

console.log(arr1.length); // Prints: 0
console.log(arr2.length); // Prints: 0

You can alternatively use the square bracket notation to empty an array, such as arr1 = [], if you don't have any references to the original array arr1 anywhere else in your code, because it creates a brand new empty array instead of emptying the original array, as you can see here:

var arr1 = [1,2,3,4,5];

// Reference arr1 by another variable
var arr2 = arr1;

// Making arr1 empty
arr1 = [];

console.log(arr1.length); // Prints: 0
console.log(arr2.length); // Prints: 5

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties