Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Modeling an Application Entity with JavaScript Objects and Methods

Recommended resources

Hello! Last time, you created and changed an array of task statuses. A real task needs more than a status: it might also have an ID and a title, and it needs ways to report or change its state. This lesson brings those related values and behaviors together in a JavaScript object.

Keep using app.js and node app.js. Allow about 40 minutes to watch the selected video segments, read the focused reference passages, and build the example. You’ll make one task entity now; later, you can put many such entities in an array.


Give one task named properties

An array identifies items by position: taskStatuses[0]. An object lets you identify related values by name: task.title or task.status. Watch the first part of Dave Gray’s Javascript Objects Explained | Javascript Objects Tutorial for the syntax.

Javascript Objects Explained | Javascript Objects Tutorial

Dave Gray introduces object literals, shows that their properties can hold different kinds of values, and compares dot and bracket notation.

Watch object basics for named properties, then property values for arrays and other values inside an object. In property access, focus on when brackets are useful; we’ll use a variable as a property name shortly.

Replace app.js with:

const task = {
  id: 101,
  title: "Draft release notes",
  status: "todo",
  tags: ["writing", "release"],
};

console.log(task.title);   // Draft release notes
console.log(task.status);  // todo
console.log(task.tags[0]); // writing

The braces create an object literal. Inside it, each property has a name and a value, separated by a colon; commas separate properties. These values need not all be the same kind: id is a number, title and status are strings, and tags is an array.

Notice the two kinds of access in task.tags[0]. task.tags gets the array named tags; [0] gets its first item. Run node app.js to confirm the output.



Read and update a property

Dot notation is usually clearest when you know the property name while writing the code. Bracket notation becomes useful when the name is stored in a variable. Read the relevant parts of MDN’s JavaScript object basics before trying both.

JavaScript object basics - Learn web development | MDN

MDN explains the distinction between properties and methods, how to change object members, and how a method uses this to reach its object’s data. Its examples use a browser console; you can apply the same object syntax in app.js with Node.js.

In “Object basics,” start at the paragraph beginning “The value of an object member can be pretty much anything.” Read properties and methods through the shorter method syntax. In “Bracket notation,” read when to use brackets, then look at the logProperty() example immediately below it. In “Setting object members,” begin “So far we've only looked at retrieving” and read updating members, including the assignment example between those sentences. Finally, in “What is ‘this’?,” read the method examples. Stop before “Introducing constructors”; creating many objects from one definition is for later.

Append the following beneath the existing console.log calls:

const field = "status";

console.log(task[field]); // todo
console.log(task.field);  // undefined

task.status = "in_progress";
console.log(task.status);  // in_progress

Run the file again. task[field] uses the value of field, so it reads task["status"]. By contrast, task.field looks for a property literally named field, which this object does not have. Reading a missing property gives undefined.

Assignment through the dot changes the existing object’s status. As with the const array in the previous lesson, const task prevents you from assigning a different object to task; it does not freeze the object’s properties.



Give the task methods

A property describes what the task has. A method is a function on the object that describes what it does. Watch the next segment of Dave Gray’s tutorial to see a method called and to see this used to access object data.

Javascript Objects Explained | Javascript Objects Tutorial

The next part of Dave Gray’s tutorial adds a method to an object and uses this to read one of that object’s properties.

Watch methods and this. Focus on the call to the method and on why its result can reflect a property value rather than fixed text. Our code will use the shorter method syntax shown in the MDN reading.

Now replace all of app.js with this complete version. The fresh start resets the task to "todo" so you can follow its changes in order.

const task = {
  id: 101,
  title: "Draft release notes",
  status: "todo",
  tags: ["writing", "release"],

  describe() {
    return `${this.title} [${this.status}]`;
  },

  markDone() {
    if (this.status === "done") {
      return false;
    }

    this.status = "done";
    return true;
  },
};

console.log(task.describe());
console.log("Changed?", task.markDone());
console.log(task.describe());
console.log("Changed again?", task.markDone());

Run node app.js. You should see:

Draft release notes [todo]
Changed? true
Draft release notes [done]
Changed again? false

describe() returns a string, so the caller decides what to do with it; here, console.log prints it. It reads the task’s current values each time it is called. markDone() changes status and returns true if it made a change. A second call finds the task already done, leaves it alone, and returns false.

The word this matters. In the call task.describe(), this refers to task while the method runs. Writing this.title means “the title of the object this method was called on.” Within markDone(), this.status = "done" updates that same object. Keep the call in the form task.describe() for now: taking a method out of its object and calling it separately can change what this means.

Methods can use parameters just like the functions you wrote earlier. For example, if you later add a rename(newTitle) method, newTitle would be the proposed title while this.title would be the task’s stored title. The distinction is between information supplied for this call and information held by the entity.



The object is a model, not a locked box

This task object groups its data and behavior in one place. Code that wants a description can call task.describe() instead of rebuilding the same text. Code that wants to complete the task can call task.markDone() and check whether anything changed.

JavaScript does not require callers to use that method, though. They can still write task.status = "done" directly—or accidentally assign a misspelled status. For this small model, the method provides a clear intended action, not a guarantee that every change is valid. Later in the course, TypeScript will help you specify which values and object shapes your program expects.

An object can also be an array item. Append this to your current file:

const tasks = [task];

for (const item of tasks) {
  console.log(item.id, item.describe());
}

The array holds the task object itself, not just its status string. Because markDone() already changed that object, the loop prints its description with [done]. As your program grows, an array can hold multiple task entities, each with its own named data.



What to carry forward

An object literal groups related values under named properties. Use dot notation for a known property name and brackets when the name comes from a variable. A method is a function on an object; when called as task.method(), it can use this to read or change that task’s properties. In this lesson, describe() reported the task’s state, while markDone() performed a deliberate state change.

You have now built the JavaScript foundations for working with collections of application entities. Next, you’ll use array operations such as map, filter, and find to work with collections without manually writing every loop.