2

I am new to Javascript, is there a way to store data in an array and be able to access it later. Example :

I have created an array

  • If I click on my HTML file button (add a question), a function generates a random Id for a question block (like id="13819").
  • It is then added to an array of question Id's
  • Once the function is done running, does the Id stay in the array once added? Or does the array reset when the function called again?
  • If it does reset, how do you make it to not reset?
GoofBall101
  • 308
  • 3
  • 15

2 Answers2

1

It depends on where your variable is created. If it is a top level variable(global) you will be able to add new data during the whole users session. On the other side if that variable is created inside a function it will be erased every time you call that function.

Vinícius Mussato
  • 338
  • 1
  • 2
  • 12
1

Short answer: Yes

Long answer: It depends

It depends on where you created the array. This is known as the scope of the array.

If it is inside the function, the scope of the array is inside the function, so only things inside the function can access the array. Once the function is finished, the array no longer exists.

You can create it in the global scope, i.e. as an attribute of the global window object, but you should try as much as possible to limit the scope of your variables, so that you don't pollute the global namespace

smac89
  • 39,374
  • 15
  • 132
  • 179
  • You can also return arrays from functions. Scope applies to variables, not objects. – Barmar Oct 23 '17 at 21:50
  • @Barmar, "*Scope applies to variables, not objects.*" are you saying that if the array is created inside the function, it will be accessible outside of it? That is without returning the array? – smac89 Oct 23 '17 at 21:51
  • You have to return the array or assign it to a global variable.[ – Barmar Oct 23 '17 at 21:53
  • or assign it to a property of an object passed in by the caller. – Barmar Oct 23 '17 at 21:54