In JavaScript, length and size are properties used to get the number of elements, but they apply to different types of objects.
1️⃣ length
- Used for arrays, strings, and array-like objects.
- Returns the number of elements or characters.
// Array
const arr = [1, 2, 3, 4];
console.log(arr.length); // 4
// String
const str = "Hello";
console.log(str.length); // 5
Notes:
- For arrays,
lengthreflects the highest index + 1, even if some elements are empty.
const arr2 = [];
arr2[3] = "Hi";
console.log(arr2.length); // 4
2️⃣ size
- Used for Set and Map objects.
- Returns the number of entries in the collection.
// Set
const mySet = new Set([1, 2, 3, 3]);
console.log(mySet.size); // 3 (duplicates ignored)
// Map
const myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);
console.log(myMap.size); // 2
Notes:
sizeis read-only. You cannot set it directly.- Unlike arrays,
SetandMaponly count actual elements/keys, no empty slots.
3️⃣ Quick Comparison
| Property | Works On | Counts | Example |
|---|---|---|---|
length |
Array, String | Number of elements/characters | [1,2,3].length → 3 |
size |
Set, Map | Number of entries | new Set([1,2,2]).size → 2 |
4️⃣ In short:
Use
lengthfor arrays and strings, andsizefor Sets and Maps — they both tell you how many elements are present, but on different object types.