Passing a function as a parameter, and set a default value

Viewed 26

This basic code

function myFun(test) {
    test();
}

myFun();

gives me the error

Uncaught TypeError: test is not a function

How do I set a default value for the test parameter? I want to be able to run myFun, without passing it any function

3 Answers

3 ways to handle that:

// providing a fallback
function myFun(test = () => {alert('no value')}) {
    test();
}
myFun();

// check if function passed
function myFun2(test) {
    test && test();
}
myFun2();

// fail safe sugar syntax
function myFun3(test) {
    test?.();
}
myFun3();

You need to pass the parameter. You can do it using lambda function. If my myTest function doesn't exist, the lambda function will be called.

    function myFun(test){
        test();
    }
    myFun(myTest||()=>console.log('test'));

A function as default value. Snippet uses an empty function.

function myFun(test = () => {}) {
    test();
}

myFun();
myFun(_ => console.log(`tested`));

Related