Search code examples
javascriptreturn

Difference between return and return false


Let's say in a javascript function I have:

function myfunction (x) {
    if (x===0) {
         return false; //return;
    };
    //some code
};

Is there a difference between return or return false?

I'm asking because someone advised me to use just return (and he do not explained why).

I'm using it for exit the function without doing nothing more. In this simple example I could use if (x!==0) {}; but in longer function maybe (tell me if I'm wrong) is not a good idea to have nested if statement.


Solution

  • Just consider this code

    function myFunc(){
      return; // exists function and returns `undefined`
    }
    const myVar = myFunc() // myVar === undefined
    

    and with false

    function myFunc(){
      return false; // exists function and returns `false`
    }
    const myVar = myFunc() // myVar === false
    

    in both caes you this will be same:

    if (!myFunc()) { console.log('this gets executed if falsy value is passed') }
    

    So they are almost the same for this use case (note that if you make any other kind of comparison with === it is different story), and which one should you prefer to use?

    I would recommend always return something, in this case false because if your function doesn't have return statement then it will always return undefined. So for sake of easier debugging, it's better to return false rather than undefined, because you will imminently know that return statement was indeed executed, while with undefined you have 1 more step to check.