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);
}