I'm going through some code at work that someone else wrote, and I'm still relatively new to JS, and I have a question about a pattern I'm seeing.
I'm finding the below pattern of using .join() and then .split(',') on an array to make a new array in a few places in this old code, usually dealing with parsing data returned from an HTTP request, but not always. I can't understand the reasons for this. Here's the snippet I'm wondering about, and then a larger snippet to give context.
var first = ['listColumn1','listColumn2','listColumn3'].join();
var headers = first.split(',');
function getEntityLookup(){
$.ajax({
type:"GET",
url:uri,
dataType: "json",
async: true,
success: parseData,
failure: function(data) {console.log("Error - could not be found");}
})
}
function parseData(result){
console.log(result);
var first = ['listColumn1','listColumn2','listColumn3'].join();
var headers = first.split(',');
for ( var i = 0, length = result.length; i < length; i++ ){
var myRow = result[i].join();
var row = myRow.split(',');
var data = {};
for ( var x = 0; x < row.length; x++ ){
data[headers[x]] = row[x];
}
jsonData.push(data);
}
Why would anyone do this? first
and myRow
are not referenced again after this operation.
I can see the purpose for this if you're trying to copy an array and want to have two separate references, so you're not just getting a copied reference (I know just enough to know that there's the potential for two variables referencing the same actual array in memory if you do this wrong, but I imagine there's probably a better way to make a separate memory allocation than .join() then .split(',') ); however, the first array is never referenced again in any of the code I've looked at with this pattern, so that doesn't seem to be the purpose in this case.