Skip to content Skip to sidebar Skip to footer

Adding Functions To An Array

This code adds functions to an array : var fArr = [] fArr.push(test()) fArr.push(test()) function test(){ console.log('here') } However the function

Solution 1:

Yes, you can add functions to an array. What you're actually doing is invoking the functions and adding the result of the function invocation to the array. What you want is this:

fArr.push(test);
fArr.push(test);

Solution 2:

It's as simple as:

fArr.push(test, test);

Examples

var fArr = []

function test() {
    return 'here';
}


fArr(test, test);     
// > Array [ function test(), function test() ]
// Because test evaluates to itself

fArr(test(), test());
// > Array [ "here", "here" ]
// Because test() evaluates to 'here'

Post a Comment for "Adding Functions To An Array"