(I was a little uncertain how to word my question.) I've just started learning JavaScript after studying other languages, and already I'm a little confused about its behavior. I wrote this code:
var todoList={
todo:[],
display:function(){
console.log(this.todo);
},
addItem:function(itemText){
this.todo.push({text:itemText,completed:false});
this.display();
},
changeItem:function(index,newText) {
this.todo[index].text=newText;
this.display();
}
};
todoList.addItem('item 1');
todoList.addItem('item 2');
todoList.changeItem(0, 'new item 1');
and when I run it, I expect to see in the console three arrays (which I do), because of the console.log()
statements. I expect to see displayed
- an array with 1 item ('item 1') after
todoList.addItem('item 1')
is run, then - an array with 2 items ('item 1', 'item 2') after
todoList.addItem('item 2')
is run, and - an altered array with 2 items ('new item 1', 'item 2')
after
todoList.changeItem(0, 'new item 1')`.
Instead, however, I see displayed 3 arrays but each one has the same items ('new item 1','item 2'). It's as if all the code is run before anything is console.logged.
What am I missing?