A JavaScript object is a named collection of values, and almost everything that you handle in this language ends up being one. Reading properties is straightforward. Changing them is where beginners get surprised, because const stops you from rebinding a variable but does nothing at all to the object that the variable points at.
This is the first lesson in the JavaScript Objects module, and the next lesson in this module is about "Adding, Updating and Removing Object Keys".
How do you read a property from a JavaScript object?
There are two notations and they reach the same value. Dot notation reads a named property, such as user.name. Bracket notation reads a property whose name you are holding as a string, such as user['name']. The two of them are interchangeable whenever the key is a valid JavaScript identifier, which is why the first three lines below all print the same thing.
const user = { name: 'Ada', 'favourite language': 'JavaScript' };
console.log(user.name); // Ada
console.log(user['favourite language']); // JavaScript
console.log(user['name']); // Ada
console.log(user.role); // undefined
The last line is the one worth remembering. Reading a property that does not exist gives you undefined rather than an error. That is convenient when you are working with optional data, and it is unhelpful when you have misspelled a key. user.nmae returns undefined and your code carries on happily until something further downstream breaks.
When do you need bracket notation instead of dot notation?
Three situations force the bracket form. The first one is a key that is not a valid identifier, such as one that contains a space or a hyphen. The second one is a key that you only know at runtime. The third one is a numeric key. JavaScript turns numeric keys into strings behind the scenes, so codes[404] and codes['404'] reach the same property.
const field = 'email';
const profile = { name: 'Ada', email: '[email protected]' };
console.log(profile[field]); // [email protected]
const codes = { '404': 'Not found', '500': 'Server error' };
console.log(codes[404]); // Not found
The general rule is short. Use dot notation for the fixed names that you wrote yourself, and reach for brackets the moment the key comes from a variable, a form field, a URL segment, or user input.
How does nested data work?
An object property can hold another object, and you keep drilling down with the same notation. The catch is that a missing key at the top level gives you undefined, while a missing key one level deeper gives you an error instead, because you are asking for a property of undefined.
const account = {
owner: { name: 'Ada', address: { city: 'London', postcode: 'E1' } },
};
console.log(account.owner.address.city); // London
console.log(account.owner.address.postcode); // E1
If account.owner.address were missing, then the first line would throw a TypeError rather than print undefined. That difference is exactly why optional chaining exists, and it is covered in the optional chaining lesson later in this tutorial.
Why does const not stop me changing an object?
Because const controls the variable and not the value. It means that this name can never be pointed at a different object. It says nothing at all about whether you may reach into the object and change what is inside it. That is why the first assignment below succeeds and the reassignment fails.
const settings = { theme: 'light' };
settings.theme = 'dark';
console.log(settings.theme); // dark
try {
settings = { theme: 'blue' };
} catch (error) {
console.log(error.constructor.name + ': ' + error.message);
}
// TypeError: Assignment to constant variable.
The same rule explains a very common surprise. If you hand an object to a function and the function changes one of its properties, then the caller sees that change too, because both names refer to the same object. The copying lesson further down this module deals with that properly.
How do you make an object genuinely read-only?
Object.freeze() seals an object. Its existing properties cannot be changed, removed, or re-added, and no new properties can be added. The catch is that the freeze is shallow, which means that a nested object inside a frozen object can still be changed.
const config = Object.freeze({ retries: 3 });
try {
config.retries = 5;
} catch (error) {
console.log('blocked: ' + error.message);
}
// blocked: Cannot assign to read only property 'retries' of object '#'
console.log(config.retries); // 3
console.log(Object.isFrozen(config)); // true
Look closely at the wording of the error, because it depends on how your file is loaded. In an ES module, or anywhere that strict mode applies, assigning to a frozen property throws an error. In sloppy mode, which means a plain script with no 'use strict' at the top, the assignment fails quietly and the value simply stays at 3. Either way the object does not change, but in strict mode you find out straight away instead of wondering why your edit vanished.
What is the difference between a data property and a method?
Structurally there is no difference at all. A method is simply a property whose value is a function. Calling it with dot notation makes this refer to the object that the method was called on, and that is what lets a method read and update the object's own properties.
const timer = {
seconds: 0,
tick() {
this.seconds += 1;
return this.seconds;
},
};
console.log(timer.tick()); // 1
console.log(timer.seconds); // 1
Inside tick, this is the timer object, so the method updates timer.seconds and the caller sees that change on the next line. this has some sharp edges when a method is detached and passed around as a callback, and a later module in this tutorial is devoted to those edges.
What is worth remembering about JavaScript objects?
| Notation | Use it for | If the key is missing |
|---|---|---|
obj.key | Fixed, identifier-safe names | Gives undefined |
obj['key'] | Keys with spaces or hyphens, numeric keys, runtime keys | Gives undefined |
obj.a.b.c | Nested data | Throws a TypeError if a level is missing |
const obj | The binding cannot be reassigned | Its properties can still change |
Object.freeze(obj) | Properties cannot change | Nested objects still can |
Try it yourself: create a file called profile.js with a const user object that holds name, age, email, and an address object with city and country. Print every value with dot notation, and then print the same values with bracket notation to confirm that both of them work. Change user.age and print it again. Then try to reassign the whole user variable and read the error message. Finally, freeze a copy with Object.freeze and try to change the age on it, noticing that the error message differs depending on whether the file is an ES module or a plain script.