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)
})
2
  • 1
    You've to type check the both arguments. Commented Nov 14, 2016 at 6:04
  • @RobG I already referred the link stackoverflow.com/questions/148901/…. But I could example of only second parameter as optional param. In my case the second param is required or mandatory param Commented Nov 14, 2016 at 6:09

2 Answers 2

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)
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

test(null, function (result) {
    console.log(result)
})

2 Comments

Is there a better way to do it ?
As per the limited information in your question it's impossible to know what would be a better for your need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.