Javascript push function help


#1

I'm not exactly sure why i keep getting error whenever I tried creating push function as shown in the picture.


#2

The parameter is shadowing your global list, and since it is a string, it does not have a push method. Change the name of your parameter.

function addTodos (todo) {
    todos.push(todo);

}


#3

Or instead you could do:

function addTodos (todos) {
this.todos.push(todos);


#4

Could you elaborate a bit more on: " since it is a string, it does not have a push method."

I checked here and the push can be used in an array with strings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /Array


#5

Yeah, after looking over it for a very long time, it dawned on me that that was my problem. Thanks!


#6

I think in order for this method to work I would first change my addTodo function from a standalone to method. I'm not quite sure I'm if properly using the correct text since i'm new to this, but it would look like this:

var todolist = {
todos: ["item1", "item2", "item3"],
displayTodos: function() {
console.log("My Todos", this.todos)
},
addTodos: function(todo) {
this.todos.push(todo);
this.displayTodos();
}
};


#7

The problem I was having with my code was I created a global variable var todos and at the same time in my addTodos function I added an argument todos, the JavaScript is accessing my function argument not the global variable. I had way to many todos lol.


#8

Definitely totally agree. Me as naive as could possibly be, wanted to give an alternate (perhaps more sophisticated solution)

I thought I had it all figured, but now came across the same issue with pure js, allow me to elaborate.

For the testing I made doing this.todos.push(todos): was using an html page with console.log output, and it worked fine, meaning it did return the additional string that was parsed as the function argument.

So I went ahead and made a fiddle>> https://jsfiddle.net/drpeck/r7gppjaw/1/ my surprise was that by running the recommended solution of using as pure JS did not work, yet the same code embeded in an HTML file did work.

So now it got me scratching my head, and would finish saying that changing the variable is straightforward approach.


#9

On your displayTodos function, why did you have +todos? is that the same as using a comma after the string "my todo"?

function displayTodos (){
console.log("my todo"+todos);
}


#10

The plus sign is used for concatenation, otherwise i get an error because the console does not understand how to process the information given.

Reference
https://www.w3schools.com/js/js_operators.asp