Is it possible to "assign" a function to another function?

Viewed 159

I'm pretty new to coding and I'm looking for advice.

I'm having a set of functions inside an animation loop that are executed depending on a variable value. This means I'm actually checking the value each frame and execute the associated function.

Since the value of the variable only changes on user input, I was thinking about taking the if else - statement out of the animation loop. I was wondering if I could "assign" the associated function to another function that runs in the loop but is able to change its content.

Any thoughts on this? :-)

2 Answers

Functions in JavaScript are objects. That means variables can refer to functions.¹

So if you have functions a, b, and c, you can have a current variable referring to the one you're currently using, for instance, a:

let current = a;

Later, if things change, you can update current to refer to b instead:

current = b;

Either way, you then use current exactly like you'd use a or b:

current(/*arguments go here if any*/);

Live Example:

const btnCall = document.getElementById("btnCall");
let current;

useA();

function a() {
    console.log("Function `a` called");
}

function b() {
    console.log("Function `b` called");
}

function useA() {
    current = a;
    btnCall.value = "Call a";
}

function useB() {
    current = b;
    btnCall.value = "Call b";
}

hook("btnCall", () => {
    current();
});
hook("btnUseA", useA);
hook("btnUseB", useB);

function hook(id, fn) {
    document.getElementById(id).addEventListener("click", fn);
}
<input type="button" value="Call ?" id="btnCall">
<input type="button" value="Use a" id="btnUseA">
<input type="button" value="Use b" id="btnUseB">

Also on CodePen (snippets are down for a lot of people right now).


¹ In fact, any time you're not using an object property to refer to a function, you're always using a "variable" (more accurately, a binding) to refer to a function. When you do:

function example() {
}

...you're creating a function and a variable in the current scope that refers to the function. The variable created by a function declaration like that is effectively identical to a var variable. Variables (var, let), constants (const), and function parameters are all bindings that hold values, including references to objects such as functions.

Not sure it will help you but you can give it a try Create an object that holds that functions you want in the value and the key to each function should be the value from the input. for example:

let obj = {
    someValue : function1,
    someOtherValue: function2
} 
function function1(){
    console.log('function 1')
}

function function2(){
    console.log('function 2')
}

function getUserInput(value){
    obj[value]();
}
getUserInput('someValue');
getUserInput('someOtherValue');

Related