0

I have a javascript function which takes two arguments. First one is necessary and the second one is optional. The second argument is a callback function. How do I provide callback function as a default argument. The code that I wrote had errors. The code that I tried:

function doSomething(count,() => {}) {
//code
}
5
  • That is an okay default function, what is the error you are getting? Tracebacks or exceptions should give a clue as to why it is not working. Commented Jul 1, 2020 at 6:41
  • @Nishant It says that the parameter declaration is expected Commented Jul 1, 2020 at 6:42
  • Oh wait, you are declaring it , sorry I was thinking this is a calling code. Yes, in that case just check for undefined. like mentioned below. Commented Jul 1, 2020 at 6:43
  • @Nishant so can I call the same function only one parameter in another place Commented Jul 1, 2020 at 6:47
  • Yeah. In JS, if you don't supply an argument, it will be undefined. Commented Jul 3, 2020 at 4:38

5 Answers 5

2

You can use default value for function parameter like below way.

function doSomething(count, fn = (() => {})) {
  //code
  //here fn is reference to the second parameter
}

Below is an example.

function doSomething(count,fn = (() => {})) {
    console.log(fn())
}


doSomething(1, () => {return 2})

Sign up to request clarification or add additional context in comments.

Comments

1

you can use call methods for this scenario

function doSomeThing(param1, fn) {

// you should callback function
(fn ? fn : yourCustomeFunction).call(this)

}



Comments

0

Any argument not passed in to a function has the value of undefined. Just check to see if the callback is defined:

function doSomething(count,callback) {
    // code
    if (callback !== undefined) {
        callback()
    }
}

To be safer, you can also check if callback is a function:

function doSomething(count,callback) {
    // code
    if (typeof callback === 'function') {
        callback()
    }
}

Comments

0
function doSomething(count,callback) {
    // code
    if (!!callback) {
        callback()
    }
}

Check whether the second argument is there or not.

Comments

0

To provide callback as default argument, you can try :

const doSomeAction = (callback = Function()) => {
  // write code here
  callback();
}

doSomeAction();

However, there are lot of other ways of doing , I prefer this approach as it's cleaner.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.