Search code examples
javascriptreturn

JavaScript: What should I return to note this function as incorrect input?


If the user inputs 1 in this example, I want the function to stop, so should I return true, or NULL, or 1, or 0...or does it really matter?

function foo() {
    // incorrect input
    if (bar === 1) {
        return true;
    }
    // correct input
    else {
        arr.push(bar);
    }
}

I know in C, 0 is returned for programs with correct input, but for programs with incorrect input they return 1, 2, 3....
Not sure what the protocol is for JavaScript.


Solution

  • This depends on what the context of this function is. Are you using the return value somewhere else? If not you can just use return to stop the function from executing:

    if (bar === 1) {
        return;
    }
    

    And if you are using the return value somewhere else and want to act on the failure you can just return false or anything and then check if that value exists.

    In your updated context you can just use the following code and it will push to the array if true and do nothing if false

    if (bar !== 1) {
        arr.push(bar);
    }