Can I store JavaScript functions in arrays?

Viewed 71994

How can I store functions in an array with named properties, so I can call like

FunctionArray["DoThis"]

or even

FunctionArray[integer]

?


Note: I do not wish to use eval.

9 Answers

The answer is has a simple answer, but it doesn't to be simplified by the answers in this thread. The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.

Example:

let a = 1;
let b = 2;

let arr = [
  a,
  b,
  function () {
    return a + b;
   },
  ];

console.log(arr[2]()); // return 3
console.log(typeof arr); // returns object

Related