Search code examples
arraysundefinedconsole.logsplice

Add Array Item into console.log


Hi guys, I am trying to develop on a lesson regarding basic To Do lists. If, after deleting a ToDo item I wanted the console to print "Deleted To Do Item" how would I do that? This is what I have thus far for the delete portion of the To Do.

function deleteToDo() {
    var index = prompt("Enter index of todo to delete");
        todos.splice(index, 1);
        console.log("Deleted " + todos[index]);
}

The error I receive is that "todos[index] is undefined" which I kind of guess would happen, at this point I'm just winging various options and seeing what happens. Do I need to define something before the splice?


Solution

  • Save the value before deleting:

    function deleteToDo() {
       var index = prompt("Enter index of todo to delete");
    
       if (index >= 0 && index < todos.length) {
           var deletedItem = todos[index];
           todos.splice(index, 1);
           console.log(deletedItem);
       }
    }