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.