I want to keep adding to an array every time I run the js file using push but it is not working

I want to save what is returned from a function so when I call it again the functions return keeps saving but instead the saved return changes every time. Is there a way I could save the return of something so when I call it again the previous one is saved and the new one gets added. I wanted to use this when making an object using factory function which one parameter is made randomly, I want to save that random instance but the problem is if the file is called again that random instance is changed. I would be really grateful if anyone can show me a way I can save the output so when I run the js file again it gets added not replaced. For example:

let list = []

const pushingNum = (num) => {
  for (let x = 1; x <= num; x++) {
    list.push(x)
  }
}

pushingNum(2)

console.log(list)

The output I expect is [1,2,1,2,1,2] if I run the file three times but the output is [1,2] even after running the js file multiple times.

I also tried:

let list = []

const pushingNum = (array) => {
  for (const x of array) {
    list.push(x)
  }
}

pushingNum(['g', 'g', 'g'])

console.log(list)

Still the output is expected [‘g’, ‘g’, ‘g’, ‘g’, ‘g’, ‘g’] after running the file two times but the output is [‘g’, ‘g’, ‘g’].

>Solution :

Store the previous state of the array in localStorage:

let list = JSON.parse(localStorage.getItem("array")) || []

const pushingNum = (num) => {
  for (let x = 1; x <= num; x++) {
    list.push(x)
  }
  localStorage.setItem("array", JSON.stringify(list))
}

pushingNum(2)

console.log(list)

Leave a Reply