Skip to main content

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

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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

// 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 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.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!

Master complex transitions, transformations and animations in CSS!

Latest Remote Jobs