Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if function returns true to execute another function

Tags:

javascript

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

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

All I want is, need to check if check() function returns true, I want to execute another function.

Code I have tried is as follows:

if(check() === true) {
  function() {
    //Another function code
  }
}
like image 683
Anand S Avatar asked Jan 21 '15 14:01

Anand S


People also ask

How do you check if a function is true in Python?

If you want to check that a variable is explicitly True or False (and is not truthy/falsy), use is ( if variable is True ). If you want to check if a variable is equal to 0 or if a list is empty, use if variable == 0 or if variable == [] .

What does return true do in JS?

Using return causes your code to short-circuit and stop executing immediately. The first return statement immediately stops execution of our function and causes our function to return true .


2 Answers

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

like image 75
JRulle Avatar answered Oct 02 '22 17:10

JRulle


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...
}
like image 25
Cerbrus Avatar answered Oct 02 '22 16:10

Cerbrus