How to export variable inside a function to another module

I would like to generate an array and store the value inside a variable and export that variable in a way that i can acess it anywhere i want in my application.

const generateNewArray = () => {

  var numberOfArrayItems = 40;
  var currentArray = Array.from({ length: numberOfArrayItems }, () => Math.floor(Math.random() * 200) + 1);

  return currentArray;
}


export { generateNewArray }

But, until right now i could only export the function. And when i invoke "generateNewArray" i get the function body as answer, and when i invoke "generateNewArray()" i get another random array, different from the original.

How can i acess the "currentArray" variable from anywhere in my application?

Thanks!

Upvotes: 0

Views: 112

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21354

You need to create a local variable, set its value, and then export the variable itself:

const generateNewArray = () => {

  var numberOfArrayItems = 40;
  var currentArray = Array.from({ length: numberOfArrayItems }, 
    () => Math.floor(Math.random() * 200) + 1);
  
  return currentArray;
}

const myRandomArray = generateNewArray();
export { myRandomArray }

Upvotes: 1

Related Questions