A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Empty an Array in JavaScript
Q:

How to Empty an Array in JavaScript

0

How to Empty an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now