CodeBlanks Logo Icon CodeBlanks

Designing the task object

JavaScript course · Beginner · Lesson 101/133

Design a task object holding id, title and completion state.

Task object design

To represent a task we use an object. An object bundles related data in one package and lets us reach each part through a property.

Our task object holds three fields: id for the number, title for the name and completed for whether it is done. This design is the base for every operation on a task.

The id field

The id field gives each task a unique number. The first task is 1, the second is 2. Thanks to this number completeTask or deleteTask knows exactly which task to target.

The nextId counter produces the number. At every addition its value is given to the new task and the counter goes up by one. Two tasks never share the same number.

The completed flag

The completed field stores whether the task is finished. Its value is either true or false, so it is a boolean. New tasks always start with false.

When you finish a task this field becomes true. The task stays in the list and is marked as done. This way you can later filter out the completed ones.

Exercise Write the createTask function

Define a function named createTask. It should take a title parameter and return an object with id, title and completed fields. Use nextId for id and false for completed.

Show example solution
The function should return an object. Use nextId for id, the parameter for title and false for completed.

Example solution:
function createTask(title) {
  return {
    id: nextId,
    title: title,
    completed: false
  };
}

Test yourself

  1. What should the createTask function return?

    • An array
    • An object
    • A number
    • A string
    Show answer

    An object — createTask returns the object that represents a task, with id, title and completed fields.

  2. Complete the task object

    function createTask(title) {
      return {
        id: nextId,
        title: title,
        ____: false
      };
    }
    Show answer
    function createTask(title) {
      return {
        id: nextId,
        title: title,
        completed: false
      };
    }
  3. Match fields to their meanings

    id
    Unique number
    title
    Task name
    completed
    Is it done

All lessons in Beginner