Check if function returns true to execute another function

前端 未结 4 501
感动是毒
感动是毒 2021-02-05 14:14

I have written a form validation using JS which ends with return(true);

function check() {
  ....validation code
  return(true);
}

All I want i

相关标签:
4条回答
  • 2021-02-05 14:48

    You just need to modify your first code snippet. return is a keyword, what you are trying to do is to execute it as a function.

    function check() {
    ....validation code
    return true;
    }
    

    You'll need to change your 2nd snippet slightly, to execute the function too however... The simplest way is to wrap it as an anonymous function using curly braces:

    if(check()) {
           (function() {
                        //Another function code
           })();
     }
    
    0 讨论(0)
  • 2021-02-05 14:49

    First of all, return is not a function, you can just do this:

    return true;
    

    Now, to only execute myFunction if check returns true, you can do this:

    check() && myFunction()
    

    This is shorthand for:

    if(check()){
        myFunction();
    }
    

    You don't need to compare the return value of check with true. It's already an boolean.

    Now, instead of myFunction(), you can have any JavaScript code in that if statement. If you actually want to use, for example, myFunction, you have to make sure you've defined it somewhere, first:

    function myFunction() {
        // Do stuff...
    }
    
    0 讨论(0)
  • 2021-02-05 14:50

    You're not calling the function in your affirmative clause, only declaring it. To call an anonymous function do this:

    (function (){...})()
    
    0 讨论(0)
  • 2021-02-05 15:01

    You should use return true; and your if statement doesn't need the === true comparison.

    function check() {
      //validation code
      return true;
    }
    
    if(check()) {
      //Another function code
     }
    

    JSFIDDLE

    0 讨论(0)
提交回复
热议问题