user4324324 user4324324 - 20 days ago 11
Node.js Question

How to handle optional parameters in function

I have a function named test which accepts two parameters. If any pass any input to that function, it works perfect. But I have a scenario where input may or may not come. How to handle such scenario. Is it possible to do in node.js? I tried using typeof check but it did not work as expected.

function test(input, callback) {
if (input) {
callback(input)
}
else {
callback("No input")
}
}
test("message", function (result) {
console.log(result)
})
test(function (result) { // This scenario fails
console.log(result)
})

Answer

you can check the typeof input if it is a function

function test(input, callback) {
    let input = input;
    let cb = callback;

    if (typeof input === 'function') {
        cb = input;
        input = 'some value';
    }

    cb(input);
}

test("message", function (result) {
    console.log(result)
})


test(function (result) { // This scenario fails
    console.log(result)
})
Comments