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?
size() is a function while array. length is a property.
length is a property of arrays in JavaScript that returns or sets the number of elements in a given array. The length property of an array can be returned like so. The assignment operator, in conjunction with the length property, can be used to set the number of elements in an array like so.
The difference between Map and Set. A Set is a collection dataset that needs to be composed of unique values, where a Map is when you have pairs of associated data when we map the keys to the value. Map and Set both have similar methods; these include .has(), . get(), .
size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.
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 aboutlength
implying metric topology. David's suggestion ofcount
is nice. ISTM what we're talking about iscardinality
, but no need to get too silly w/ precision. Thoughsize
is just fine with me, and has plenty of prior art.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With