Henry Zhang
Henry Zhang

Reputation: 68

Can you call a function from a function's parameter?

This is my code, and I want to use .forEach to execute the functions in the array.

const ar = new Array ('function1', 'function2', 'function3', 'function4');
ar.forEach(element => element();)

However, when I run this code, it gives me Uncaught Typerror: element is not a function. I have tried

ar.forEach(element => {element = var x; x();})

But, it only gives me the error Uncaught Typerror: x is not a function. If you can help, thanks!

Upvotes: 1

Views: 71

Answers (4)

Ayoub ElHayat
Ayoub ElHayat

Reputation: 103

I guess you're doing something wrong! if you want to put your functions inside an array and then call them in a forEach, it should work normally. try this:

const f1 = ()=> console.log("f1");
const f2 = ()=> console.log("f2");
const ar = new Array(f1, f2);
ar.forEach((f)=> f())
// output: 
// f1
// f2

Upvotes: 0

Alaeddine
Alaeddine

Reputation: 1687

Sure you can. But instead of having Strings inside your Array as in your case here, you need to have the functions themselves

const ar = new Array (
    () => {console.log('function1')},
    () => {console.log('function2')},
    () => {console.log('function3')},
    () => {console.log('function4')}
);
    
ar.forEach(element => element();)

Upvotes: 1

Danziger
Danziger

Reputation: 21161

You could do that by just adding the actual functions to the array:

const f1 = () => console.log('f1');
const f2 = () => console.log('f2');
const f3 = () => console.log('f3');
const f4 = () => console.log('f4');
const functions = [f1, f2, f3, f4];

functions.forEach(f => f());

Or creating an object that maps the keys in your array to the actual functions you want to call:

const f1 = () => console.log('f1');
const f2 = () => console.log('f2');
const f3 = () => console.log('f3');
const f4 = () => console.log('f4');
const functions = { f1, f2, f3, f4 };
const functionKeys = ['f1', 'f2', 'f3', 'f4'];

functionKeys.forEach(key => functions[key]());

This also applies if your functions live in the global scope:

window.f1 = () => console.log('f1');
window.f2 = () => console.log('f2');
window.f3 = () => console.log('f3');
window.f4 = () => console.log('f4');

const functionKeys = ['f1', 'f2', 'f3', 'f4'];

functionKeys.forEach(key => window[key]());

Upvotes: 4

MrCodingB
MrCodingB

Reputation: 2314

You can do this but your array would have to consist of functions not strings

e.g.:

const functions = [ () => console.log('Hi'), () => console.log('Hello world') ];

functions.forEach(f => f());

Upvotes: 3

Related Questions