0

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)
})
user4324324
  • 559
  • 3
  • 7
  • 25
  • 1
    You've to type check the both arguments. – Teemu Nov 14 '16 at 06:04
  • @RobG I already referred the link http://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript. But I could example of only second parameter as optional param. In my case the second param is required or mandatory param – user4324324 Nov 14 '16 at 06:09

2 Answers2

0

You can just pass a null as a parameter like so:

test(null, function (result) {
    console.log(result)
})
Esko
  • 4,109
  • 2
  • 22
  • 37
0

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)
})
Jairo Malanay
  • 1,327
  • 9
  • 13