1

I have an Object literal and I'm trying to add todos to a todos array.

Why is this array, initialized at the beginning of the object undefined?

let todoList = {
  // create an empty array
  todos: [],

  // display all todos
  displayTodos: () => {
    // check if array is empty
    if (this.todos.length === 0) {
      console.log('Todos is empty');
    } else {
      // loop through array
      for (var i = 0; i < this.todos.length; i++) {
        // check completion status
        // prefix x if completed
        if (this.todos[i].completed === true) {
          console.log('(x)', this.todos[i].todoText);
        } else {
          console.log('( )', this.todos[i].todoText);
        }
      }
    }
  },

  // add todo to todo Objects
  addTodos: (todoText) => {
    this.todos.push({
      todoText: todoText,
      completed: false
    });
    this.displayTodos();
  },

  // change todo at certain position
  changeTodos: (position, todoText) => {
    this.todos[position].todoText = todoText;
    this.displayTodos();
  },

  // change the completion status of todo
  toggleCompleted: (position) => {
    this.todos[position].completed ? false : true;
    this.displayTodos();
  }
};

todoList.addTodos('Test todo 1');
todoList.addTodos('Test todo 2');
todoList.addTodos('Test todo 3');
todoList.changeTodos(1, 'Test todo 4');
todoList.toggleCompleted(1);

It errors when I try to push an object onto the todos array, stating that the array is undefined.

0 Answers0