Start learning free

LESSON 98 OF 344 · DICTIONARIES

Dictionaries in JavaScript: Objects as Key-Value Pairs

Lesson Read the full explanation

In JavaScript, objects serve as dictionaries — they store key-value pairs where each key maps to a value.

const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};

Objects use curly braces {}. Keys and values are separated by colons :, and pairs are separated by commas. You can also use a Map for more dictionary-like behavior, but objects are most common.

const person = {"name": "Alice", "age": 25, "city": "NYC"};
console.log(person["name"]);            // "Alice"
console.log(Object.keys(person).length); // 3

You can add new key-value pairs after creation:

const scores = {};
scores["Alice"] = 95;
scores["Bob"] = 87;

Assignment
Follow the Coding Tutorial and create an object scores with three student scores!


Hint
Use const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · DICTIONARIES

    Dictionaries in JavaScript, explained

    What a dictionary is

    A dictionary stores values under names. Each name is a key, and the thing stored under it is its value. You look a value up by its key, the way you look up a word to find its meaning. Lists and arrays find items by position. A dictionary finds them by label, which is much clearer when the data has meaning: a score belongs to a student, not to "item number 2".

    JavaScript has no separate type called "dictionary". Plain objects do the job. They are by far the most common way to store key-value pairs, and you will meet them everywhere in JavaScript code.

    Creating an object

    An object literal is written with curly braces. Inside, each pair is a key, a colon, and a value. Pairs are separated by commas:

    const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
    

    Here the keys are the names "Alice", "Bob" and "Charlie", and the values are their scores. An object can hold values of different types, so a record about one person can mix strings and numbers:

    const person = {"name": "Alice", "age": 25, "city": "NYC"};
    console.log(person["name"]);              // Alice
    console.log(Object.keys(person).length);  // 3
    

    You can start with an empty object and fill it in later:

    const scores = {};
    scores["Alice"] = 95;
    scores["Bob"] = 87;
    console.log(scores);   // { Alice: 95, Bob: 87 }
    

    Keys, quotes and order

    Keys are always strings (or special values called symbols, which beginners can ignore). When a key is a simple name made of letters, digits and underscores, the quotes are optional, so {Alice: 95} is the same object as {"Alice": 95}. Quotes are required when the key has a space or other special characters, such as "first name".

    A number used as a key is turned into a string, so {1: "one"} has the key "1". This also affects the order in which keys are listed. Keys that look like whole numbers come first, in increasing order, and then all other keys appear in the order they were added. For {b: 1, a: 2, 10: "x", 2: "y"}, Object.keys returns [ '2', '10', 'b', 'a' ]. If you need a collection where order and key types are fully under your control, JavaScript also offers Map. Objects are enough for this lesson and for most everyday work.

    const does not freeze the contents

    The lesson declares the object with const. That stops you from assigning a different object to the variable, but you can still add, change and delete entries inside it:

    const d = {x: 1};
    d.x = 100;     // fine
    d.y = 200;     // fine
    console.log(d);   // { x: 100, y: 200 }
    // d = {};     // TypeError: Assignment to constant variable.
    

    The variable holds a reference to the object, and const protects the reference, not the object itself.

    The exercise, step by step

    The task is to build an object named scores with three student scores. There is no starter code to extend, so the object is the whole answer.

    1. Declare the constant. Write const scores =. You use const because the variable is never going to point at a different object.
    2. Open the object literal with a curly brace.
    3. Add the three pairs, each as a key in quotes, a colon and a number: "Alice": 95, "Bob": 87 and "Charlie": 72. Put a comma between the pairs.
    4. Close the brace and end the statement with a semicolon.

    The solution in JavaScript

    const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
    

    Nothing is printed by this line. It only creates the object. Add console.log(scores) to see { Alice: 95, Bob: 87, Charlie: 72 }.

    Common mistakes

    • Using the wrong separator. Keys and values are separated by a colon, not an equals sign, and pairs are separated by commas, not semicolons. {"Alice" = 95} is a syntax error.
    • Using square brackets by mistake. Square brackets create an array. A dictionary uses curly braces.
    • Repeating a key. If two pairs have the same key, the later value silently replaces the earlier one. An object holds each key only once.
    • Treating it like an array. An object has no length property. Use Object.keys(scores).length to count entries, which a later lesson covers.

    Key takeaways

    • A JavaScript object works as a dictionary of key-value pairs, written with curly braces, colons and commas.
    • Keys are strings. Quotes are optional for simple names and required for keys with spaces.
    • You can add or change entries after creation, even on a const object.
    • A key appears once. Reusing it replaces the value.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free