0

Below are two approaches to set an array empty:

Approach 1:

var arr = [2,3];
arr = [];
arr.map(x => {
  console.log(x);
})

Approach 2:

var arr = [2,3];
arr = null;
if(arr != null) {
  arr.map(x => {
    console.log(x);
  })
}

Both the approaches work. But when working on a large dataset and complex array for Visualisations , there would be many events where modification of this array happens and I am not sure which way to go.

Edit: Sorry for my poor explanation above. Below is my code for expanding/collapsing the tree nodes of a treeview in d3 like here. In the below code, if setNodePositions() checks the length of d.children array when it is set to null, then an error is thrown. But in the toggleChildren() if you set the d.children = [] then no error is thrown. So, I was wondering if choosing one over the other may result in performance issues or some unwanted behaviour later. The question was more to gain some knowledge on the topic. The code works if I set the d.children = [] instead of setting it to null.

function toggleChildren(d) {
    if(d.children) {
        d._children = d.children;
        d.children = null;
    } else if(d._children) {
        d.children = d._children;
        d._children = null;
    }      
    setNodePositions();
    render(plotter);
}
optimalLight
  • 194
  • 1
  • 1
  • 13
  • 2
    are you looking for this benchmark? https://stackoverflow.com/a/1232046/17447 – naveen Mar 07 '21 at 09:26
  • Best way under what circumstances? And what are the goals? Also, are you sure the difference really matters? See [Which is faster?](https://ericlippert.com/2012/12/17/performance-rant/) – VLAZ Mar 07 '21 at 13:54
  • @naveen Thanks for the link. very informative – optimalLight Mar 07 '21 at 14:50

2 Answers2

0

Another way could be

let arr = [2, 3];
if(arr.length != 0){
    // do something
}
Ashutosh Patole
  • 926
  • 1
  • 7
  • 23
0

The length property can be used on other data types, it is good to also check that your array is indeed an array as you were expecting.

I suggest you also use the Array.isArray() method to confirm your array is an array. This method determines if whether what was passed in is an array or not. If what was passed in was an array, this method will return true

if(Array.isArray(arr) && !arr.length){
 // do something
}