Last Updated: February 25, 2016
·
746
· aemmons

javascript hasOwnProperty Efficiency/Elegence

I have an object that is going to store key, value pairs, which are points in time and values. I will add integer values to the points in time but am not sure what all the keys (points in time) are before hand so I can't initialize the object to zeros. I starting doing it this way, using object.hasOwnProperty:

var sdata = {}, point = 0;
for(var j=0;  j<plen; j++){
    point = chart.series[i].points[j];
    if(sdata.hasOwnProperty(point.x)){
        sdata[point.x] += point.y;
    }else{
        sdata[point.x] = point.y;
    }
}

But I am curious whether the IF statement in the loop could be made more efficient and/or more elegant. So I came up with the following:

var sdata = {}, point = 0;
for(var j=0;  j<plen; j++){
    point = chart.series[i].points[j];
    sdata[point.x] = point.y + sdata[point.x] || point.y;
}

It doesn't seem to be faster on FF15 and I am not sure the elegance of removing the IF statement is worth the hit to readability. Thoughts?

1 Response
Add your response

I guess there is a performance benefit:

http://jsperf.com/hasownproperty-efficiency

So does anyone have a comment on readability?

over 1 year ago ·