JS · Lesson 6

Objects

Grouping related values under one name

A story has a title, an author and a number of views. Instead of three separate variables, you can keep them together in one object, the way a card keeps a person's details together.

What you'll learn

  • How to keep many related values together in one object.
  • How to read, change and add properties.
  • How to show an object on the page, and how to keep a list of objects.

Welcome to objects

An object groups related values under one name. Each value has its own name too, called a key. A key and its value together make a property.

You've been using objects since JS Lesson 1: document is an object, and innerHTML is one of its elements' properties. Even console is an object, and log is a property that holds a function.

Think of a school ID card. One card holds many facts about one student, and each fact has a label: Name, Grade, Section. In JavaScript, the card is the object, each label is a key, and what's written next to it is the value.

Each line of the card becomes one property: a key, a colon, then the value. Commas go between the properties.

A closer look

How an object is written

Inside an object, a colon : joins a key to its value. That's different from =, which you use for variables. Keys follow the same rules as variable names.

Two ways to read a property

Dot notation, like story.title, is the short, usual way. Bracket notation, like story["title"], does the same thing with the key in quotes. Brackets are useful when the key is stored in a variable, like story[field].

Changing a const object

In JS Lesson 2, a const couldn't get a new value. An object made with const still can't be swapped for a different object, but you can change its properties, or add new ones. Think of it like this: you keep the same ID card, but you can update what's written on it.

Objects and arrays together

An array can hold objects, like a list of stories where each story is an object. A for...of loop from JS Lesson 4 can then visit each one. An object can also hold arrays, like a team with a list of players.

Let's build it

Let's describe a Front Page Bytes story as an object. The HTML and CSS stay the same in every step: a heading and an empty box, #card.

Step 1: Make an object

Your code
const story = {  title: "New phones arrive",  author: "Ana",  views: 120,  isNew: true};console.log(story);
What you see

Console

    Nothing here yet. console.log() writes here.

    story holds four properties: two strings, a number and a boolean. The console shows the whole object, with each key and its value.

    Step 2: Read a property with a dot

    Your code
    const story = {  title: "New phones arrive",  author: "Ana",  views: 120,  isNew: true};console.log(story.title);console.log(story.views);
    What you see

    Console

      Nothing here yet. console.log() writes here.

      story.title means "the title of story". The console shows New phones arrive, then 120.

      Step 3: Change and add properties

      Your code
      const story = {  title: "New phones arrive",  author: "Ana",  views: 120,  isNew: true};story.views = 150;story.topic = "Tech";console.log(story);
      What you see

      Console

        Nothing here yet. console.log() writes here.

        story.views = 150; changes a value that's already there. story.topic = "Tech"; adds a property that wasn't there before. The console shows the updated object, with the new topic at the end.

        Step 4: Read with brackets

        Your code
        const story = {  title: "New phones arrive",  author: "Ana",  views: 120,  isNew: true};console.log(story["author"]);const field = "views";console.log(story[field]);
        What you see

        Console

          Nothing here yet. console.log() writes here.

          story["author"] works like story.author. In line 9, the key is stored in the variable field, so story[field] reads story.views: 120.

          Step 5: Show the object on the page

          Your code
          const story = {  title: "New phones arrive",  author: "Ana",  views: 120,  isNew: true};document.getElementById("card").innerHTML =  "<h2>" + story.title + "</h2>" +  "<p>By " + story.author + " · " + story.views + " views</p>";
          What you see

          Console

            Nothing here yet. console.log() writes here.

            The properties are joined with HTML tags into one string, and innerHTML puts it in #card. The statement is split over three lines to make it easier to read. JavaScript reads it as one line, up to the ;.

            Step 6: A list of objects

            Your code
            const stories = [  { title: "New phones arrive", views: 120 },  { title: "Faster Wi-Fi for schools", views: 85 },  { title: "Robots help farmers", views: 230 }];for (const story of stories) {  console.log(story.title + ": " + story.views + " views");}
            What you see

            Console

              Nothing here yet. console.log() writes here.

              stories is an array, and each item is an object with the same keys. The for...of loop takes one story at a time and reads its title and views.

              Quick notes

              { } An object
              const story = { title: "New phones", views: 120 };

              How to use

              • { key: value } An object: properties inside curly braces.
              • key: value, One property. A comma goes between properties.
              • Values can be any type: strings, numbers, booleans, arrays, even other objects.

              Examples

              1. A student.

                const student = {  name: "Ana",  grade: 7};
              2. A product in a store.

                const product = {  name: "Pandesal",  price: 5,  inStock: true};
              3. A list inside an object.

                const team = {  name: "Eagles",  players: ["Ana", "Ben", "Carla"]};
              object.key Read a property
              console.log(story.title);

              How to use

              • object.key Reads a property. This is called dot notation.
              • object["key"] Also reads it. The name goes in quotes.
              • object[name] Reads the property whose name is stored in the variable name.
              • A property that doesn't exist gives undefined.

              Examples

              1. Read with a dot.

                console.log(student.name);
              2. Read with brackets.

                console.log(product["price"]);
              object.key = value Change or add a property
              story.views = 150;

              How to use

              • object.key = value; Changes a property, or adds it if it's new.
              • This works on a const object too. const keeps the same object, but its properties can change.

              Examples

              1. Change a value.

                student.grade = 8;
              2. Add a new property.

                student.section = "Rizal";

              Common mistakes

              These are mistakes many beginners make. Each mini browser shows what really happens, and the console shows the message the browser gives.

              Misspelling a key

              The mistake
              const story = {  title: "New phones arrive",  author: "Ana"};console.log(story.tilte);
              What you see

              Console

                Nothing here yet. console.log() writes here.

                story.tilte has two letters swapped. JavaScript doesn't stop with an error. It looks for a property called tilte, doesn't find one, and gives undefined.

                Tip: Copy the key exactly as it's written in the object. Capital letters count too.

                Forgetting a comma between properties

                The mistake
                const story = {  title: "New phones arrive"  author: "Ana"};console.log(story.title);
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  Without the comma after line 2, JavaScript doesn't know where one property ends and the next begins. The whole script stops with a SyntaxError before anything runs.

                  Tip: Put a comma after every property except the last one.

                  Using = instead of : inside an object

                  The mistake
                  const story = {  title = "New phones arrive",  author = "Ana"};console.log(story.title);
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    Inside an object, keys and values are joined with :, not =. With =, the script stops with a SyntaxError.

                    Tip: Inside { }, join a key to its value with a colon: title: "New phones arrive".

                    Test your knowledge

                    Write JavaScript in the JS tab. Make an object for a pet, with properties like its name, kind and age. Then read, change and show its properties.

                    No clicking needed. Each goal gets a check mark by itself once your code does it.

                    1. Make an object with at least three properties. not done yet
                    2. Read one property with a dot, and log it. not done yet
                    3. Change one property, or add a new one. not done yet
                    4. Show some of the properties on the page in #pet. not done yet
                    Your code
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      Go to Exercises

                      Recap

                      • An object groups related values: { key: value, key: value }. Each key and value pair is a property.
                      • Read a property with object.key or object["key"]. A key that doesn't exist gives undefined.
                      • object.key = value; changes a property or adds a new one, even on a const object. Arrays can hold objects, and objects can hold arrays.

                      References

                      Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                      • ECMA International. ECMAScript Language Specification (official specification). Open reference