Start learning free

LESSON 101 OF 344 · DICTIONARIES

Dictionary Length in JavaScript: Counting Object Keys

Lesson Read the full explanation

In JavaScript, you can get the number of key-value pairs in an object using Object.keys().length:

const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
let count = Object.keys(scores).length;
console.log(count);  // 3

Object.keys() returns an array of the object's keys, and .length gives the count.

const d = {a: 1, b: 2};
console.log(Object.keys(d).length);    // 2
console.log(Object.values(d).length);  // 2  (same result)

Assignment
Follow the Coding Tutorial and get the number of entries in scores!


Hint
Use Object.keys(scores).length and assign it to count.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · DICTIONARIES

    Dictionary Length in JavaScript, explained

    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.

    1. Get the keys. Object.keys(scores) returns ["Alice", "Bob", "Charlie"].
    2. Take the length of that array. Adding .length gives 3.
    3. Store it. Declare count with let and 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 is undefined and does not raise an error, so the mistake can hide for a while.
    • Forgetting that Object.keys takes the object as an argument. Write Object.keys(scores), not scores.keys(). Objects have no keys method of their own.
    • Calling .length() with parentheses. On an array, length is a property, so Object.keys(scores).length() throws a TypeError.
    • Expecting the count to update itself. Recompute it after you add or delete entries.

    Key takeaways

    • Plain objects have no length. Use Object.keys(obj).length to count entries.
    • Object.values and Object.entries give the same count.
    • An empty object has a count of 0, and adding, deleting or repeating keys changes it as you would expect.
    • A Map uses .size instead.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free