How to add item to array - need help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to add item to array - need help

I try many times to figure how, using buttons, to add a new Item to array. Maybe You will be know how to fix that code in JS. https://code.sololearn.com/W9PUdNjsG3Bi/?ref=app

31st Mar 2018, 5:00 PM
Kamil Janiak
Kamil Janiak - avatar
4 Answers
+ 4
In your shopping_list() function you create the array called list however nothing outside the function can access it and it also gets deleted when the function is done, so to fix that problem put the list array at the start of the JS script outside any function to make the array global meaning it gets deleted when the user leaves the web page and anything can access and change it.
31st Mar 2018, 5:52 PM
TurtleShell
TurtleShell - avatar
+ 4
When using the var keyword to define the variable list within the shopping_list function you are creating a local variable to that function and limiting its scope so that it may only be accessed within that function. Removing the var keyword would expand the scope of the list variable outside of the function so that the list variable could be accessed from within the add_to_list function, however the list would still be redefined each time the shopping_list function was called so the output would never change. Moving the variable and defining its initial value outside of the functions using the var or let keyword, as TurtleShell suggested, will give you the result you're looking for.
31st Mar 2018, 6:57 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
WOW That was so simple and genius. Now it's clear. Make that variable global and it's done :D Very big thanks
31st Mar 2018, 7:22 PM
Kamil Janiak
Kamil Janiak - avatar
+ 2
Thanks a lot both of you guys.
31st Mar 2018, 7:31 PM
Kamil Janiak
Kamil Janiak - avatar