Check if function true returns true to execute another function

I wrote a form validation using JS that ends with return (true);

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

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

The code I tried looks like this:

 if(check() === true) { function() { //Another function code } } 
+6
source share
4 answers

You must use return true; , and the if statement does not need to compare === true .

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

JSFIDDLE

+12
source

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

 return true; 

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

 check() && myFunction() 

This is a shorthand for:

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

You do not need to compare the return value of check with true . This is a logical value.

Now, instead of myFunction() you can have any JavaScript code in this if . If you really want to use, for example, myFunction , you have to make sure that you define it somewhere, first:

 function myFunction() { // Do stuff... } 
+5
source

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

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

You will need to slightly modify the second code fragment to execute the function too ... The easiest way is to wrap it as an anonymous function using curly braces:

 if(check()) { (function() { //Another function code })(); } 
0
source

You do not call a function in your affirmative clause, only by declaring it. To call an anonymous function, follow these steps:

 (function (){...})() 
-2
source

Source: https://habr.com/ru/post/981349/


All Articles