Why objects have no length
With arrays and strings you ask for .length and get the number of items. A plain object doesn't work that way. If you try, you get undefined:
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
console.log(scores.length); // undefined
An array is an ordered list that always knows its size. An object is a bag of named properties, and JavaScript doesn't keep a ready-made count for it. Instead, you ask the object for a list of its keys and count that list.
Object.keys and length
Object.keys(obj) returns an array containing the object's keys as strings. An array has a length, so chaining the two gives the number of entries:
let count = Object.keys(scores).length;
console.log(count); // 3
console.log(Object.keys(scores)); // [ 'Alice', 'Bob', 'Charlie' ]
There are two companions that give the same count. Object.values(obj) returns the values, and Object.entries(obj) returns key-value pairs. Each of them has one item per entry, so the lengths agree:
const d = {a: 1, b: 2};
console.log(Object.keys(d).length); // 2
console.log(Object.values(d).length); // 2
console.log(Object.entries(d).length); // 2
Use Object.keys when you only want to count, since the keys are the cheapest thing to read out and the intent is clearest.
What gets counted
The count follows the entries that exist right now, so it changes as the object changes:
const z = {a: 1, b: 2};
console.log(Object.keys(z).length); // 2
z.c = 3;
console.log(Object.keys(z).length); // 3
delete z.a;
console.log(Object.keys(z).length); // 2
An empty object has a count of zero: Object.keys({}).length is 0. A key whose value is undefined still counts, because the entry exists. And since a key can appear only once, assigning to an existing key does not change the count.
Object.keys returns only the object's own keys. It does not include names every object inherits, such as toString. That is exactly what you want when the object is a dictionary.
Maps have a size
A Map is a separate built-in type for key-value data, and it does keep its count. You read it with .size, with no parentheses and no length:
const m = new Map(Object.entries(scores));
console.log(m.size); // 3
Mixing the two up is a common slip. Objects use Object.keys(obj).length, and maps use map.size.
The exercise, step by step
The starter code already has the object:
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
The task is to store the number of entries in a variable named count.
- Get the keys.
Object.keys(scores)returns["Alice", "Bob", "Charlie"]. - Take the length of that array. Adding
.lengthgives3. - Store it. Declare
countwithletand assign the whole expression to it.
The solution in JavaScript
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
let count = Object.keys(scores).length;
The variable count holds the number 3 at the moment of the assignment. It is a snapshot, not a live view. If you add a key to scores afterwards, count stays at 3 until you run the expression again.
Where the count is useful
Knowing how many entries a dictionary holds answers several practical questions. Is the dictionary empty? Then its count is zero, which is a simple test before you try to read from it. How many different items have you seen so far? If you add each item as a key, the count tells you how many distinct ones there are, because repeated keys collapse into one. How many students have a recorded score? The same expression answers it, no matter how the object was filled.
The count can also guard a loop or a report. You might print "3 scores recorded" or stop when the dictionary reaches a given size. In each case the pattern is the same: ask for the keys, then take the length of the resulting array.
Common mistakes
- Writing
scores.length. It isundefinedand does not raise an error, so the mistake can hide for a while. - Forgetting that
Object.keystakes the object as an argument. WriteObject.keys(scores), notscores.keys(). Objects have nokeysmethod of their own. - Calling
.length()with parentheses. On an array,lengthis a property, soObject.keys(scores).length()throws aTypeError. - Expecting the count to update itself. Recompute it after you add or delete entries.
Key takeaways
- Plain objects have no
length. UseObject.keys(obj).lengthto count entries. Object.valuesandObject.entriesgive the same count.- An empty object has a count of 0, and adding, deleting or repeating keys changes it as you would expect.
- A
Mapuses.sizeinstead.