On Mar 16, 8:43 pm, Rob Griffiths <r...@bytespider.eu> wrote: > > Why it is better to use a function instead of direct access? > > It's not always better.
Where "better" is not defined. If the OP means faster, then in the linked tests the "best" method is evenly split between direct access and push(). The other contender is hamstrung by having to lookup x.length every time so not really a surprise it's never fastest. And given that push() is a built-in method, it's no surprise that it can be faster than a javascript alternative. > Push is far better when you're not sure what the next index of your array > is. for example: > > [87, 2, 369, , , , 42, 53] > > If i remember correctly .length will return 5, Not in any implementation conforming to ES 3 or 5. Array.length is *defined* as being the highest index plus one, so adding a value at length + 1 must create a new index with a higher value than any other index (and increment length by one). The only reasons I know of to not use push() is that it is not available in some very old browsers so a fallback to a POJS alternative should be provided, sometimes the "direct access" method is faster and the code requires 3 fewer characters (which is never a good reason to do anything but some think it matters). -- Rob -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com