Do I use .size() or .length in Javascript?

Sam Deering
Tweet

Do I use .size() or .length in Javascript?

Let’s have a closer look…

.size() simply calls .length (clearly shown this in the jQuery source code below) so we are saving a function call

//http://code.jquery.com/jquery-latest.js
// The number of elements contained in the matched element set
        size: function() {
                return this.length;
        },

.length() has been proved to be faster than .size() (clearly shown is a jsperf http://jsperf.com/size-vs-length test). So why is the .size() function in jQuery? My initial guess would be that they are keeping it abstract so that if a different way of calculating the .length is required in the future it may provide a backwards compatible API.

Common usage you may have seen:

//check if a DOM element is present
if ($('#id').length > 0) { ... }

So in a nutshell, I use .length until someone gives me a substantial reason not to.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://danmathisen.com/ dmathisen

    I agree – definitely use .length because, as you said, it save an unnecessary function call.

    Also…
    if ($(‘#id’).length > 0) { … }
    can be simplified to:
    if ($(‘#id’).length) { … }