JavaScriptLesson 10 of 18

JavaScript Objects

An object groups related values under one name. Instead of three loose variables for a person, you store name, age, and city inside one object. Each value lives in a property made of a key and a value. Real programs use objects constantly, because almost all real-world data is a set of related facts.

An object groups related values under one name. Instead of three loose variables for a person, you store name, age, and city inside one object. Each value lives in a property made of a key and a value. Real programs use objects constantly, because almost all real-world data is a set of related facts.

Write an object with curly braces and list each property as key: value, with commas between them. Read a value with dot notation, like person.name. When the key has a space or a dash, use bracket notation instead: person["full name"]. Both read the same data, so pick whichever fits the key.

Reading a key that does not exist gives you undefined, not an error, so check values that come from user input. Objects stay flexible after creation: assign a new value to a key and it updates in place. A property can hold any type, including an array or another object, which is how you build nested data.

Reading properties

Dot notation is the clearest way to read a value: object name, a dot, and the key. If you ever need a dynamic key, one stored in a variable, bracket notation is the way, because dot notation only accepts a literal key name.

JS
const phone = {
  brand: "Pixel",
  price: 699
};
console.log(phone.brand); // "Pixel"
const key = "price";
console.log(phone[key]); // 699

Updating objects

Objects stay flexible after creation. Assign a new value to a key and the object updates in place. Arrays and objects inside an object update the same way, which is how you keep structured data like a player profile current.

JS
const player = { score: 0, name: "Ada" };
player.score = 10;
player.name = "Ada Lovelace";

Syntax

JS
const user = {
  name: "Ada",
  age: 36,
  city: "London"
};
console.log(user.name);

Reading Missing Key Gives undefined, Not Error

obj.missing is undefined, not error — check with "key" in obj or hasOwnProperty.

JS
if ("name" in obj)

Good to know

  • Objects group related facts under one name.
  • Dot notation reads a property; bracket notation handles odd keys.
  • A missing key returns undefined, not an error.
  • Property values can be arrays or other objects.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground