Reading a value by its key
A dictionary is only useful if you can get values back out of it. In JavaScript you read a value from an object by naming the key, in one of two ways: bracket notation or dot notation.
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
let aliceScore = scores["Alice"]; // 95 (bracket notation)
let bobScore = scores.Bob; // 87 (dot notation)
Both expressions look up the key and give you the value stored under it. The object itself is not changed by reading.
Bracket notation versus dot notation
Bracket notation puts the key inside square brackets as a string, so it works for any key at all, including keys with spaces or other special characters:
const odd = {"first name": "Ann"};
console.log(odd["first name"]); // Ann
Dot notation is shorter, but the key must be a valid identifier, which means a name that starts with a letter, _ or $ and has no spaces. odd.first name would be a syntax error.
The bigger difference is that brackets accept any expression, so the key can come from a variable. A dot always means the literal name that follows it:
const k = "Bob";
console.log(scores[k]); // 87
console.log(scores.k); // undefined
In the first line, k is evaluated and its value "Bob" is used as the key. In the second, JavaScript looks for a key literally named "k", which doesn't exist. This is why loops and functions almost always use brackets.
Keys that are not there
Reading a key that doesn't exist does not cause an error. You get the special value undefined:
console.log(scores["Diana"]); // undefined
console.log(scores["alice"]); // undefined
The second line shows that keys are case sensitive: "alice" and "Alice" are different keys. Because a missing key is silent, a misspelled key gives a confusing undefined later in the program instead of a clear error near the cause.
To test whether a key exists, use the in operator:
if ("Alice" in scores) {
console.log(scores["Alice"]); // 95
}
This is more precise than checking the value. A key can exist with the value undefined, and in still reports true. Another option is Object.hasOwn(scores, "Alice"). Be aware that in also finds names that every object inherits, so "toString" in scores is true. For plain data lookups, Object.hasOwn is the stricter test.
When you want a fallback for a missing key, use the nullish operator: scores["Diana"] ?? 0 gives 0, while scores["Alice"] ?? 0 gives 95.
The exercise, step by step
The starter code already has the object:
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
The task is to read Alice's score into a new variable.
- Pick the key. The key is the string
"Alice", with the same capital A as in the object. - Read it with brackets:
scores["Alice"]. The expression evaluates to95. - Store it. Declare
aliceScorewithletand assign the expression to it.
The solution in JavaScript
const scores = {"Alice": 95, "Bob": 87, "Charlie": 72};
let aliceScore = scores["Alice"];
After this line, aliceScore is the number 95. It is a copy of the value, so changing aliceScore later doesn't touch the object. The line scores.Alice would give the same result, because Alice is a valid identifier.
Common mistakes
- Forgetting the quotes in brackets.
scores[Alice]looks for a variable namedAliceand stops with aReferenceErrorif there is none. The key must be a string:scores["Alice"]. - Using a number-style index.
scores[0]looks for the key"0", not the first entry. Objects are looked up by key, not by position. - Getting the case wrong.
scores["alice"]returnsundefined. - Using dot notation with a variable.
scores.namenever uses a variable calledname. Switch to brackets.
Looking at everything at once
Sometimes you want all the keys or all the values, not one lookup. Object.keys(scores) returns an array of the keys, Object.values(scores) an array of the values, and Object.entries(scores) an array of key-value pairs. A for...of loop over the entries reads every pair, and the keys come out in the order described in the previous lesson. You will use these once you need to process a whole dictionary instead of a single value.
Key takeaways
- Read a value with
obj["key"]or, for simple names,obj.key. - Brackets work for every key and accept variables. Dot notation needs a valid identifier.
- A missing key gives
undefined, not an error. Keys are case sensitive. - Use
inorObject.hasOwnto check that a key exists.