jocull
jocull

Reputation: 21135

Why do JavaScript Sets/Maps use `size` instead of `length`?

While looking over new changes to JavaScript I noticed that Set and Map use .size instead of .length like arrays would.

This seems like a pointless diversion from what's normal with arrays - just one more thing to remember.

Was there a good design reason for this?

Upvotes: 12

Views: 1189

Answers (2)

ubershmekel
ubershmekel

Reputation: 12818

While apsillers' Jan 27, 2016 answer adds great links, a code example is missing. The size of a set is a read-only getter while that's not the case for arrays which allow modifying the length to truncate the array.

let arr = [1, 2, 3, 4]
arr.length = 2
console.log("modified length array", arr) // [1, 2]

let mySet = new Set([1, 2, 3, 4])
mySet.length = 2
mySet.size = 2
console.log("modified length set", [...mySet]) // [1, 2, 3, 4]

let str = "1234"
str.length = 2
console.log("modified length string", str) // "1234"

Upvotes: 1

apsillers
apsillers

Reputation: 115980

There's a lot of discussion in the esdiscuss thread "Set length property". This was a hotly debated issue, so it's not surprising that you do not necessarily agree with the resolution.

There is a tremendous amount of arguing about this in esdiscuss. Ultimately, the argument that prevailed (as evidenced by the fact that ES2015's Sets have size and not length) was summarized in a post by David Bruant:

...for me 'length' refers to a measurement with something like a ruler. You start at 0 and see up to where it goes. This is very accurate for an array which is an indexed set (starting at 0 and growing) and for arrays as considered in C (continuous sequence of bytes) which ECMAScript arrays seem inspired of. This is probably less relevant for unordered collections such as sets which I'd tend to consider as a messy bag.

And further discussed in a post by Dean Landolt:

Just wanted to jump in and say non-writable length is consistent with String behavior as well, but David makes a good point about length implying metric topology. David's suggestion of count is nice. ISTM what we're talking about is cardinality, but no need to get too silly w/ precision. Though size is just fine with me, and has plenty of prior art.

Upvotes: 18

Related Questions