465

What is the difference between the two?

So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?

  var x = [];
  console.log(x.size());
  console.log(x.length);
  console.log(x.size()==x.length);
  x =[1,2,3];
  console.log(x.size());
  console.log(x.length);
  console.log(x.size()==x.length);

Will print:

  0, 0, true
  3, 3, true
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • 73
    Where have you found `Array.size()` method in native JavaScript? – VisioN Jan 07 '13 at 19:23
  • 2
    Chrome doesn't have `.size`... – David G Jan 07 '13 at 19:24
  • Fair point, just tried plugging both into Firebug, and .size() does not work. It does appear to work fine in Chrome's console... – Abraham P Jan 07 '13 at 19:25
  • 1
    @AbrahamP idk what Chrome console you are using... – Naftali Jan 07 '13 at 19:25
  • @AbrahamP What webpage are you on when doing `.size()` in the console? I'm assuming that page played with `Array`'s proto. – Snuffleupagus Jan 07 '13 at 19:27
  • 2
    [Screenshot of my Chrome console after running your code](http://i.stack.imgur.com/JZpKn.jpg) – gilly3 Jan 07 '13 at 19:29
  • 3
    `.size()` is likely from Prototype framework: http://prototypejs.org/doc/latest/language/Array/prototype/size/ – MikeM Jan 07 '13 at 19:30
  • 2
    Why does this question have so many upvotes, when it's most likely the OP has Prototype or some other framework that added the `size()` method to `Array`. Personally think it's very misleading to new readers. The answer doesn't address the question directly. Consider revising or deleting the question? – Damon Aw Oct 31 '13 at 19:28
  • @daemonsy I guess this page is nice because it's a quick answer to the google search of "how to get array's size in javascript". Other than that I agree – Samie Bencherif Dec 29 '15 at 07:20

10 Answers10

613

Array.size() is not a valid method

Always use the length property

There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).

Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).

Gabriel
  • 18,322
  • 2
  • 37
  • 44
183

.size() is not a native JS function of Array (at least not in any browser that I know of).

.length should be used.


If

.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.

or

There might be some plugin on your browser that is mucking with the Array prototype.

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • @BartFriederichs well I am in Chrome, but that is good to know :-D – Naftali Jan 07 '13 at 19:25
  • It DOES work in Chrome, does not work in Firefox, I tend to use Chrome for debugging needs so it appeared to work. Thanks for pointing out its non existence. – Abraham P Jan 07 '13 at 19:25
  • @AbrahamP again -> I do not know what Chrome you are using, but for me, this does not work at all in Chrome! – Naftali Jan 07 '13 at 19:26
  • 9
    If it works in Chrome for you, there is probably some extra library you are calling on your page that adds it to the Array prototype. – Spike Williams Jan 07 '13 at 19:27
  • 2
    Version 23.0.1271.97 [].size function size(){return this.length;} So actually its just a wrapper around .length... I kinda feel stupid now... – Abraham P Jan 07 '13 at 19:28
  • Version 23.0.1271.97 m of Chrome reports `TypeError: Object 1,2,3,4,5 has no method 'size'` when attempting to use `.size()` on an array. – Kevin Boucher Jan 07 '13 at 19:28
  • I'm using 23.0.1271.97 of Chrome too. That doesn't exist. – aquinas Jan 07 '13 at 19:29
  • @AbrahamP I have the same version as you, but I do not have a size fn. Make sure you are not including some random library somewhere... – Naftali Jan 07 '13 at 19:29
  • 2
    @AbrahamP, hit F12 on THIS page, and type `[].size` in the console. If it works, then you have some sort of Chrome Plugin that is mucking with the Array prototype, and I would be worried. :) – aquinas Jan 07 '13 at 19:30
  • It was just the page I was mucking around on(pivotaltracker). Thanks for all the responses! – Abraham P Jan 07 '13 at 19:31
38

The .size() function is available in Jquery and many other libraries.

The .length property works only when the index is an integer.

The length property will work with this type of array:

var nums = new Array();
nums[0] = 1; 
nums[1] = 2;
print(nums.length); // displays 2

The length property won't work in the following case:

var pbook = new Array(); 
pbook["David"] = 1; 
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0

The reason is that JavaScript does not support indexes of type string in arrays but objects (as properties), and pbook or an object of prototype Array named "pbook" would now have two properties assigned ("David" and "Jennifer"; i.e. pbook.David) and represent an empty array.

const a = []; // Relatively the same as: const a = new Array();

a['0a'] = 123; a['2'] = 456; a[1] = 789;

console.log(`a(${a.length}) = `, a);
console.log(`Enumerable properties of ${Object.prototype.toString.call(a)} = `, Object.keys(a));

So in your case you should be using the .length property.


For objects, please consider the following:
- Length of a JavaScript object;
- Object.getOwnPropertyNames vs Object.keys.

Artfaith
  • 1,183
  • 4
  • 19
  • 29
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
21

.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.

If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.

j0k
  • 22,600
  • 28
  • 79
  • 90
Julio Flores
  • 435
  • 4
  • 7
19

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
user2811108
  • 191
  • 1
  • 3
  • In practice it is the number of items. Most JS interpretors will fill array rows with undefined. In your example, you will have 101 element in your array with 97 elements without value (undefined) but elements are there. It will looks like : ['car1', 'car2', 'car3', undefined * 97, 'car100'] If you loop on this array, your increment variable will value 101 after the loop. – ElJackiste Mar 31 '18 at 09:57
  • 1
    On the other hand, array.length isn't necessarily the number of **defined** (not assigned) value in the array. – ElJackiste Mar 31 '18 at 10:04
  • It is precisely the number of items in the array. Whether or not those items are undefined is up to the programmer to account for, not JS. – Layne Bernardo Mar 11 '21 at 01:31
11

The property 'length' returns the (last_key + 1) for arrays with numeric keys:

var  nums  =  new  Array();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ;
log.info( nums.length );

will print 12!

This will work:

var  nums  =  new  Array();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ;
nums [ 12 ]  =  12 ;
log.info( nums.length + '  /  '+ Object.keys(nums).length );
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
cskwg
  • 790
  • 6
  • 13
  • Whilst this is an interesting answer, I'm not completely sure it's an answer to _this_ question – OliverRadini Nov 14 '18 at 09:03
  • 1
    The OP was asking 'Array.size() vs Array.length'. From the previous discussions, it was make clear, that the 'size' Function is not part of standard JavaScript but implemented by libraries. So I'm assuming that the OP is interested in how to retrieve the real length of JavaScript arrays. I'm uncovering a little known 'feature' of JavaScript which can lead to unexpected behavior, especially as the behavior is different when the array contains other types of objects, like strings, for example. – cskwg Nov 16 '18 at 05:53
  • You might be interested in this: function asz( o ) { return null !== o && 'object' === typeof o && def( o.length ) ? Object.keys( o ).length : 0; } – cskwg May 28 '21 at 07:46
4

The .size() method is deprecated as of jQuery 1.8. Use the .length property instead

See: https://api.jquery.com/size/

Davy
  • 1,720
  • 1
  • 19
  • 42
1

Size detects duplicates, it will return the number of unique values

const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
console.log(set1.size);
// expected output: 6
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
rev
  • 27
  • 1
1

Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.

The size accessor property returns the number of (unique) elements in a Set object.

const set1 = new Set();
const object1 = new Object();

set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);

console.log(set1.size);
// expected output: 3

And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];

console.log(clothing.length);
// expected output: 4
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
1

we can you use .length property to set or returns number of elements in an array. return value is a number

> set the length: let count = myArray.length;
> return lengthof an array : myArray.length

we can you .size in case we need to filter duplicate values and get the count of elements in a set.

const set = new set([1,1,2,1]); 
 console.log(set.size) ;`
Sunali Bandara
  • 402
  • 4
  • 6