4

If I have to delete all the items in an array, what's the difference between using new Array and length = 0? In the example, apparently the result looks the same.

function MyCtrl($scope) { 
    
    $scope.arrayData = ["1", "2", "3"];
    
    $scope.newArray1 = function(){
     $scope.arrayData = new Array();
    }    
    
    $scope.newArray2 = function(){
     $scope.arrayData = [];
    }
        
    $scope.lengthZero = function(){
     $scope.arrayData.length = 0;
    }    
            
    $scope.populate = function(){
     $scope.arrayData.push("1", "2", "3");
    }    
 }
 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
Data:
</h2><br>
   <ul>
        <li ng-repeat="data in arrayData">{{data}}</li>
    </ul> 
    <button ng-click="newArray1()">New Array - 1st method</button>
    <button ng-click="newArray2()">New Array - 2nd method</button>
    <button ng-click="lengthZero()">Length = 0</button>
    
    <button ng-click="populate()">Populate</button>
</div>
panagulis72
  • 2,129
  • 6
  • 31
  • 71

2 Answers2

5

There is quite a big difference between just using [] and .length = 0.

If you use = [] you will assign a new reference to the variable, losing your reference to the original. By using .length = 0 you will clear the original array, leaving the original reference intact.

Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
  • As you said there is big difference between using `[]` and `.length = 0`. Can you come up with a practical scenario when this difference affect the result. – Aryan Firouzian Jan 10 '19 at 10:56
1

With array = new Array(); you will create a new reference.

A better way to clear an array and keep the reference would be:

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

while (array.length) {
    array.pop();
}

Also take a look at this exact same question: Difference between Array.length = 0 and Array =[]?

Community
  • 1
  • 1
Fidel90
  • 1,828
  • 6
  • 27
  • 63