completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Object basics

Create JavaScript objects, read and change properties with dot or bracket access, check which keys exist, understand property order, and delete properties safely.

By the end you’ll be able to
  • 01
    Make objectsWrite object literals with plain keys, quoted keys, shorthand properties, and computed keys.
  • 02
    Read and change propertiesChoose a dot or square brackets, change values, and avoid the common user.field mistake.
  • 03
    Check what an object holdsUse in, Object.hasOwn, Object.keys, for...in, and delete, and know what each one gives you.

Objects group related data

An object is one value that holds several related values. Each value is stored under a name.

Say you want to keep three facts about a user. You could make three separate variables: userName, userAge, and userRole. Or you can make one user object and keep all three inside it, as user.name, user.age, and user.role.

Each thing stored in an object is called a property. A property has two parts:

  • The key is the property's name, like name. It is also called the property name.
  • The value is what is stored under that name, like "Ada".
A cart called user holds two cards: name: Ada and age: 36. An arrow points to one property split in two: a tag that says name, which is the key, and a card that says Ada, which is the value.name: "Ada"age: 36username"Ada"keyvalue
One object, user, holds two properties. Each property has two parts: the key is its name, like name, and the value is what is stored under it, like "Ada".

You met objects in the Data types lesson. There you saw that an object is not a primitive. A primitive is a single simple value, like a number or a string. The Variables lesson showed that you can change an object's properties, even when the object is stored in a const.

This lesson shows the everyday things you do with an object:

  • make one,
  • read and change its properties,
  • check whether a property exists,
  • see the order of its keys,
  • and delete a property.
The main idea

An object is one value with named properties. A property key is the name. A property value is what is stored under that name.

Real-life analogyAn object is a filing cabinet

Picture a small filing cabinet for one user. One drawer has the label name. Inside it is a paper that says "Ada". Another drawer has the label age. Inside it is a paper that says 36. To find the age, you open the drawer labelled age. To change the role, you swap the paper in the drawer labelled role.

In real life: The cabinet
In JavaScript: The object, like user
In real life: The label on a drawer
In JavaScript: A key, like name
In real life: The paper inside a drawer
In JavaScript: A value, like "Ada"
In real life: Open the drawer with that label
In JavaScript: Read user.name or user["name"]

This lesson is about properties that store data. Later lessons in Module 8 cover the rest:

  • methods, which are functions stored in an object, and this,
  • constructors, which make many objects of the same shape,
  • Symbols, a special kind of key,
  • and how an object turns into a primitive, like a string.

Object literals

FOUNDATION

The simplest way to make an object is an object literal. "Literal" means you write the value straight into your code. An object literal looks like this:

  • It starts with { and ends with }.
  • Inside are the properties, with a comma after each one.
  • Most properties are written as key: value.

The key is always stored as a string. The value can be any JavaScript value: a string, a number, a boolean, null, an array, or even another object.

A user object with three propertiesPop out in the code editor (opens in a new tab)JavaScript
const user = {  name: "Ada",  "favorite color": "blue",  profile: { city: "Pune" },};console.log(user.name);console.log(user["favorite color"]);

Line 2 uses the key name. It is a valid identifier: a name made of letters, digits, _, or $ that does not start with a digit. So it needs no quotes.

Line 3 uses the key favorite color. A key can be any string, even one with a space. But this key is not a valid identifier, so it must be written in quotes.

Line 4 stores another object as the value of profile. The comma at the end of line 4, after the last property, is called a trailing comma. It is allowed, and it makes it easier to add another property later.

Line 6 prints Ada. Line 7 reads the key with the space using square brackets and prints blue. You'll see why it needs square brackets in the next section.

After an object exists, you can add or change a property with =:

  • If the key is new, JavaScript adds a new property.
  • If the key is already there, JavaScript replaces its value.

This is useful for a shopping cart, a form, or a profile that gets more details later.

Add a new property, then change onePop out in the code editor (opens in a new tab)JavaScript
const cart = { total: 3 };cart.items = 1;cart.total = 5;console.log(cart.items);console.log(cart.total);

The cart starts with one property, total. Line 2 adds items, because the cart did not have that key yet. Line 3 replaces the old total, 3, with 5. Lines 4 and 5 print 1 and 5. It is still the same cart: setting a property never makes a second object.

The same key twice: the last value winsPop out in the code editor (opens in a new tab)JavaScript
const order = { drink: "tea", drink: "coffee" };console.log(order.drink);

Here the key drink appears twice in one object literal. The object still gets only one drink property, and it keeps the last value. So line 2 prints coffee. Give each key only once. A repeated key is almost always a mistake, so fix it when you see one.

Read a property inside a propertyPop out in the code editor (opens in a new tab)JavaScript
const user = { profile: { city: "Pune" } };console.log(user.profile.city);console.log(user.settings?.theme);

An object stored inside another object is called a nested object. Line 2 reads user.profile first, then city inside it. It prints Pune.

Line 3 reads user.settings, which does not exist. The ?. after it means: "if the value on the left is undefined or null, stop here and give undefined." So line 3 prints undefined. Without ?., reading theme from undefined would throw a TypeError. You learned ?. in the Nullish & optional chaining lesson.

Dot or square brackets

INTERACTIVE

There are two ways to read or write a property:

  • Dot access, like user.name. Use it when you know the key while you write the code, and the key is a valid identifier.
  • Bracket access, like user["favorite color"] or user[field]. Inside the square brackets goes a string, or a variable that holds the key.
Read a key that is stored in a variablePop out in the code editor (opens in a new tab)JavaScript
const user = { name: "Asha" };const key = "name";console.log(user[key]);

Line 2 stores the text "name" in the variable key. That is the name of the property, not its value. On line 3, JavaScript first reads key and gets "name". Then it reads the name property of user. It prints Asha.

Real-life analogyDot goes straight to a drawer; brackets read a sticky note first

If you know the drawer is called name, you go straight to it. That is dot access. Sometimes someone hands you a sticky note that says which drawer to open. You read the note first, then open that drawer. That is bracket access with a variable.

In real life: You know the drawer's label by heart
In JavaScript: Use user.name
In real life: A sticky note says which drawer to open
In JavaScript: Use user[field]
In real life: The label has a space or a dash in it
In JavaScript: Use user["favorite color"]
Object inspector: add, change, and delete properties
What the buttons runPop out in the code editor (opens in a new tab)JavaScript
const user = {  name: "Ada",  age: "36",  role: "admin",};const key = "age";const value = "37";user[key] = value;delete user[key];console.log(Object.keys(user).join(", "));
The object now3 keys
"name""Ada"
"age""36"
"role""admin"
Object.keys(user)name → age → role
user.keyundefined
user[key]"36"
key in usertrue
Object.hasOwn(user, key)true
Try it yourself

Type a key, then add, change, or delete that property.

The playground runs real JavaScript: =, delete, Object.keys, in, and Object.hasOwn. Every value is kept as a string, so you can focus on the keys.

Try it. Type favorite color as the key and blue as the value, then press Add/change. You can't write that key after a dot, because of the space. Brackets can still read it.

Next, type key as the key and press Add/change. Now user.key shows a value instead of undefined. That is because the object now really has a property named key.

Dot or brackets? Step through the reads
Step 0 of 6Ready
Your turn: follow the blue line

Predict each line before you step. Change field, and only line 5 changes. Line 6 always looks for a key that is the word field.

Running in
  1. script
Next: line 1
const field = "age";console.log(user.name);console.log(user["favorite color"]);console.log(user[field]);console.log(user.field);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Change line 2: which key does field hold?

A new choice starts the replay again. Predict line 5 before you step.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Line 6 shows the most common mistake. user.field looks like it should use the variable field. It doesn't: a dot never reads a variable. It looks for a key that is the word "field" itself. This object has no such key, so you get undefined. When the key is stored in a variable, use brackets.

Left: user[field]. A box called field holds the card age, and an arrow leads to the value 36. Brackets read the variable, so this reads age. Right: user.field. A tag says field. A dot looks for a key named field, so the result is undefined.user[field]"age"field36uses what field holdsreads ageuser.fieldfielda key named fieldundefined
Brackets read the variable field first and use what it holds, "age". A dot never reads a variable: user.field looks for a key that is the word field, and this object has none.
Dot or brackets?
  • user.name
  • user["first-name"]
  • user[key]
  • user.2
  • user["2"]
  • user.class
Try it yourself
0 of 6 correct

Sort each expression. Can the key go after a dot? Does it need brackets, because it is a string or a variable? Or is it a syntax error, which means JavaScript can't even read the code?

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Computed & shorthand properties

STEP THROUGH

Object literals have two shortcuts you will see often:

  • A computed property name puts square brackets around the key inside the literal: { [key]: value }. JavaScript first works out the value of key. Then it uses that result as the property name.
  • A shorthand property lets you write { name } instead of { name: name }. It works when the variable and the property have the same name.
Use a variable's value as a keyPop out in the code editor (opens in a new tab)JavaScript
const field = "drink";const order = { [field]: "tea" };console.log(order.drink);

Line 1 stores the text "drink" in field. On line 2, [field] reads that variable, so the object gets a property named drink. You need the square brackets only while you make the key. Line 3 can use a dot, because you know the key is drink. It prints tea.

Step through computed and shorthand properties
Step 0 of 7Ready
Your turn: follow the blue line

Shorthand and computed names are two short ways to write ordinary properties.

Running in
  1. script
Next: line 1
const value = "blue";const name = "Ada";const age = 36;const user = { name, age, [key]: value };console.log(user.name);console.log(user["favorite color"]);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

After line 5, the properties are ordinary. The object just has the keys name, age, and favorite color. Nothing remembers how they were written. The Methods & this lesson adds one more shortcut: a short way to write a function inside an object.

A key name or a variable?

In an object literal, { key: value } makes a property whose name is the word key. { [key]: value } reads the variable key first and uses what it holds. The square brackets are the only difference.

Check whether a key exists

COMPARE

Reading a property tells you its value. Sometimes you need to ask something else: does this property exist at all? Reading the value can't always tell you, for two reasons:

  • A property can exist and hold the value undefined. A missing property also reads as undefined.
  • Ordinary objects inherit some built-in properties, like toString. Inherited means your object can use the property, but it is stored on another object, not on yours. That other object is Object.prototype; a later lesson explains it.
Three ways to check for a keyPop out in the code editor (opens in a new tab)JavaScript
const user = { name: "Ada", age: undefined };console.log("age" in user);console.log(Object.hasOwn(user, "age"));console.log(user.age === undefined);console.log("toString" in user);console.log(Object.hasOwn(user, "toString"));

The table shows what each line prints. Read each row as: "this check prints this, and here is what that tells you."

What each check prints for the user object above
The checkWhat it printsWhat it tells you
"age" in usertrueThe key exists, even though its value is undefined.
Object.hasOwn(user, "age")trueage is a property of user itself.
user.age === undefinedtrueThis is also true for a missing key, so it can't tell you whether the key exists.
"toString" in usertruein also counts inherited properties, like toString.
Object.hasOwn(user, "toString")falseObject.hasOwn skips inherited properties.

Which check should you use?

  • Use Object.hasOwn(obj, key) to ask: "Does this object itself have this key?" It ignores inherited properties.
  • Use key in obj when inherited properties should count too.
  • Don't use obj[key] === undefined to check whether a key exists. It is true for a missing key, and also for a key that holds undefined.
Object.hasOwn still works when a key hides a built-inPop out in the code editor (opens in a new tab)JavaScript
const user = { hasOwnProperty: false };console.log(Object.hasOwn(user, "hasOwnProperty"));

Objects also inherit an older method called hasOwnProperty. In older code you may see obj.hasOwnProperty(key). But this object has its own key named hasOwnProperty, and it holds false. So user.hasOwnProperty("name") would throw a TypeError, because false is not a function.

Object.hasOwn belongs to Object, not to your object, so it still works. Line 2 prints true. Use Object.hasOwn in new code.

Property order

STEP THROUGH

Objects are not arrays. If order is the main point, use an array. Still, JavaScript has fixed rules for the order of an object's keys. You see this order when you use Object.keys(obj), which gives an array of the object's own keys, or a for...in loop. The rules:

  1. First come the integer-like keys, from smallest to largest. These are keys like "3" or "20": whole numbers written the normal way, with no leading zero.
  2. Then come all the other string keys, in the order you added them.

Symbols, a special kind of key, are left out by Object.keys and for...in. Symbols have their own lesson.

Step through the order of keys
Step 0 of 7Ready
Your turn: follow the blue line

Step through the lines that add keys. Then compare the final Object.keys order with the order the lines added them.

Running in
  1. script
Next: line 1
codes.name = "Ada";codes[20] = "twenty";codes[3] = "three";codes["01"] = "leading zero";codes.added = "last";console.log(Object.keys(codes).join(" → "));
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Look at the result. 3 comes before 20, even though line 4 added 3 after line 3 added 20. Both are integer-like keys, so they go first, smallest first.

The key "01" is different. It has a leading zero, so it is not the normal way to write the number 1. JavaScript treats it as an ordinary string key. It stays in the order it was added, after name.

Top row, the order the keys were added: name, 20, 3, 01, added. An arrow labelled Object.keys points to the bottom row, the order it lists them: 3, 20, name, 01, added.the order you add themname20301addedObject.keys320name01addedthe order Object.keys gives
The keys 3 and 20 are integer-like, so Object.keys lists them first, smallest first. The other keys, name, 01, and added, follow in the order they were added.

The for…of & for…in lesson showed loops over keys. The same advice applies here: if your code depends on order, use an array of objects. Don't rely on the key order of one object.

Deleting properties

STEP THROUGH

The Rest of the operators lesson introduced delete. delete obj.key removes the property from the object. That is not the same as setting it to undefined:

  • obj.key = undefined keeps the key. Only its value changes, to undefined.
  • delete obj.key removes the key and its value.
Left: after user.age = undefined, the user cart still holds a card that says age: undefined, so the age in user check is true. Right: after delete user.age, the user cart is empty, so the age in user check is false.user.age = undefinedage: undefineduserthe key stays"age" in user → truedelete user.ageuserthe key is gone"age" in user → false
Setting a property to undefined keeps the key; only the value changes. delete takes the whole property out, key and value.
Set to undefined, then delete
Step 0 of 7Ready
Your turn: follow the blue line

Compare setting a property to undefined with deleting it. The list of keys and the in checks show the difference.

Running in
  1. script
Next: line 1
user.mood = undefined;console.log(Object.keys(user).join(", "));delete user.age;console.log(Object.keys(user).join(", "));console.log("age" in user);console.log("mood" in user);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Use delete when the object should no longer have that property. Use obj.key = undefined only when the key should stay, but it has no value right now.

A const object can still change

const user = { name: "Ada" }; stops you from giving user a new value, like user = {}. It does not stop you from changing the object's properties. You can still write user.name = "Grace" or delete user.name. Stopping all changes is called freezing an object, and that is a separate topic.

Where you’ll use objects

Use an object whenever names matter. A settings object is clearer than many separate variables, because each value has its name right next to it. These often start as objects:

  • the values someone typed into a form,
  • data that a server sends back,
  • feature flags, which switch parts of an app on or off,
  • lists of translations, from a word to the same word in another language,
  • and the current state of a part of the page.
A settings object for an appPop out in the code editor (opens in a new tab)JavaScript
const settings = {  theme: "dark",  notifications: true,  shortcuts: { save: "⌘S" },}; const field = "theme";console.log(settings[field]);console.log(settings.shortcuts?.save);

The same rules apply here:

  • Brackets for a key in a variable: settings[field] on line 8 prints dark.
  • A dot for a key you know, and ?. for a nested value that might be missing: line 9 prints ⌘S.
Show "Not set" when a field is missingPop out in the code editor (opens in a new tab)JavaScript
const response = { name: "Asha", city: "Delhi" };const city = Object.hasOwn(response, "city") ? response.city : "Not set";console.log(city);

Data from a server or a form may leave out fields that are optional. Line 2 uses the conditional operator: test ? a : b gives a when the test is true, and b when it is false. Here the test is Object.hasOwn(response, "city"):

  • If city is there, city gets response.city.
  • If it is missing, city gets "Not set".

This response has a city, so line 3 prints Delhi.

The table below helps you pick a tool. Read each row as: "in this situation, ask this question, and use this tool."

Which tool to use for which question
SituationQuestionBest toolWhy
The value might be undefinedDoes the object itself have this key?Object.hasOwn(obj, key)It skips inherited properties. It tells a missing key apart from a key that holds undefined.
Inherited properties should countCan the object use this key, from itself or from where it inherits?key in objUse it when built-in or inherited properties matter to you.
You need the valueWhat is stored under this key?obj[key]It gives the value. It does not tell you whether the key exists.

Common misconceptions

Two common mistakes in one small programPop out in the code editor (opens in a new tab)JavaScript
const user = { age: 36 };const field = "age";console.log(user[field]);console.log(user.field);user.age = undefined;console.log(Object.hasOwn(user, "age"));

Line 3 prints 36. Line 4 prints undefined. Line 6 prints true, even though line 5 set age to undefined. Each belief below is a common mistake, followed by what really happens.

  • "A dot reads variables." It doesn't. user.field looks for a key that is the word "field". Use user[field] when the key is stored in a variable.
  • "If the value is undefined, the property is missing." Not always. A property can exist and hold undefined. Use Object.hasOwn to check whether it exists.
  • "in and Object.hasOwn are the same." They are not. in also counts inherited properties. Object.hasOwn checks only the object itself.
  • "Keys always come out in the order I typed them." Integer-like keys come out first, smallest first.
  • "delete just empties the value." delete removes the key too. Setting a property to undefined keeps the key and changes only the value.
  • "A const object can't change." const only stops you from giving the variable a new value. The object's properties can still change.

Practice exercises

5 EXERCISES
Exercise 1 · Warm-upBuild a book object

In your editor or the console, make a book object with title, author, and pages. Also give it a nested status object that holds read: false.

Starter codePop out in the code editor (opens in a new tab)JavaScript
// Create a book object with title, author, pages, and a nested status object.
    Exercise 2 · PracticePredict dot and bracket results

    Read the program. Predict the three lines it prints.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const user = { name: "Ada", "first-name": "Ada", age: 36 };
    const key = "age";
    console.log(user.name);
    console.log(user[key]);
    console.log(user.key);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix the user.field bug

      Replace the broken expression with one that prints 36.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const user = { name: "Ada", age: 36 };
      const field = "age";
      console.log(user.field); // should print 36

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeCount own properties

        What number does the program print?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const profile = { name: "Asha", age: 36, city: "Pune" };
        let count = 0;
        for (const key in profile) {
          if (Object.hasOwn(profile, key)) {
            count = count + 1;
          }
        }
        console.log(count);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeDelete versus undefined

          Predict the two lists of keys. Write them as "first then second".

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const item = { label: "Hat", price: 20 };
          item.price = undefined;
          console.log(Object.keys(item).join(","));
          delete item.price;
          console.log(Object.keys(item).join(","));

          Answer, then press Check. Spacing and letter case don’t matter.

            Check your understanding

            8 QUESTIONS
            Lesson quiz · 8 questionsScore: first tries count
            1. Question 1 of 8Which line makes an object with two properties?

              Choose an answer to see the explanation.

            2. Question 2 of 8What does this bracket read print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const user = { name: "Ada", age: 36 };
              const field = "age";
              console.log(user[field]);

              Choose an answer to see the explanation.

            3. Question 3 of 8What does this dot read print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const user = { age: 36 };
              const field = "age";
              console.log(user.field);

              Choose an answer to see the explanation.

            4. Question 4 of 8Which object literal uses a computed property name?

              Choose an answer to see the explanation.

            5. Question 5 of 8What does Object.hasOwn print for a key that holds undefined?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const user = { age: undefined };
              console.log(Object.hasOwn(user, "age"));

              Choose an answer to see the explanation.

            6. Question 6 of 8In what order does Object.keys list these keys?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const codes = { 20: "twenty", 3: "three", name: "Ada" };
              console.log(Object.keys(codes).join(","));

              Choose an answer to see the explanation.

            7. Question 7 of 8What does in print after a property is set to undefined?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const item = { name: "Hat", price: 20 };
              item.price = undefined;
              console.log("price" in item);

              Choose an answer to see the explanation.

            8. Question 8 of 8Which statement removes the price property from item?

              Choose an answer to see the explanation.

            Key takeaways

            • An object literal makes one value with named properties.
            • Use a dot when you know the key and it is a valid identifier. Use square brackets when the key is in a variable, or has a space or a dash.
            • A computed name { [key]: value } and a shorthand { name } both make ordinary properties.
            • Object.hasOwn checks only the object's own properties. in also counts inherited ones.
            • Object.keys lists integer-like keys first, smallest first. The other keys follow, in the order you added them.
            • delete removes a property. Setting it to undefined keeps the key.

            Final definition: An object is a JavaScript value that keeps related values under names, called keys. You can add, read, change, check, list, and remove its properties.

            Up next: Objects & references. You'll learn why two variables can point to the same object.

            CompleteFrontend Clear concepts. Working examples.