Different ways to empty an array

var arrayList = ['b','l','o','g','g','e','r'];

Method 1 :

arrayList = [];

This can be recommended only if you don't have references of the original array anywhere else. If the array is referenced to another variable and the original will remain unchanged.

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList = []; //empty array
console.log(copy); //  ['b','l','o','g','g','e','r']

Method 2:

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList.length = 0; 
console.log(arrayList); //empty array
console.log(copy);//empty array

output : 
[ ]

This way of emptying the array also updates the reference variables that points to the original variable.

Method 3:

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
arrayList.splice(0,arrayList.length);
console.log(arrayList); 
console.log(copy);

By using this method is also perfect one, as it updates value to the reference variable.

output :

[ ]
[ ]

Method 4 :

var arrayList = ['b','l','o','g','g','e','r'];
var copy = arrayList;
 while(arrayList.length){
  arrayList.pop();
console.log(arrayList); // [ ]
console.log(copy); // [ ]

Even this empty arrays but this is not been recommended much.

1 comment:

  1. Lemme guess... the 4th one is not recommended becuz it takes more space? you keep create an array with an item less,
    [1,2,3,4]
    [1,2,3]
    [1,2]
    [1]
    []

    ReplyDelete

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...