JavaScript Objects
An object stores named values in one place. A property is one named value inside an object.
Read with a dot
An object stores named values in one place, and this literal holds three of them. Dot notation reads a value by its key after a dot.
const person = { name: "Ana", age: 9, city: "Oslo" };
console.log(person.name);
console.log(person.age);Read with brackets
Bracket notation reads a value by its key in a string. This line reads the city property.
const person = { name: "Ana", age: 9, city: "Oslo" };
console.log(person["city"]);Change and add
An assignment changes the age value here. A new key adds a city property, and typeof reports the object type.
const person = { name: "Ana", age: 9 };
person.age = 10;
console.log(person.age);
person.city = "Oslo";
console.log(person.city);
console.log(typeof person);Example
const person = { name: "Ana", age: 9, city: "Oslo" };
console.log(person.name);
console.log(person["age"]);
person.age = 10;
person.country = "Norway";
console.log(person);Key points
- Key: the name part of a property, written before the colon
- Curly braces mark the start and end of an object literal.
- A comma separates one property from the next.
- Values in one object can mix types, such as a string and a number.
- A nested object is an object stored as the value of a property.
In this example, the person object starts with a name, an age, and a city. Dot notation logs the name, and bracket notation logs the age. The next line changes age to 10, and the line after it adds a country property. The last line logs the whole object with its four properties.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is a property of an object?