Using the return value of a function in an if statement

Hope this will be a quick question.

Is it possible to use the return value of a function in an if statement? I.e.

function queryThis(request) { return false; } if(queryThis('foo') != false) { doThat(); } 

Very simple and obvious, I am sure, but I ran into a number of problems with syntax errors and cannot determine the problem.

+6
source share
5 answers

You can just use

 if(queryThis('foo')) { doThat(); } function queryThis(parameter) { // some code return true; } 
+8
source

You can not only use functions in if in JavaScript, but you can do this in almost all programming languages. This case is specially highlighted for JavaScript, as functions are the first citizens in it. JavaScript has almost all functions. A function is an object, a function is an interface, a function is the return value of another function, a function can be a parameter, a function creates closures, etc. Therefore, it is 100% acceptable.

You can run this example in Firebug to see that it works.

 var validator = function (input) { return Boolean(input); } if (validator('')) { alert('true is returned from function'); } if (validator('something')) { alert('true is returned from function'); } 

Also, as a hint, why using comparison operators in if blocks when we know that the expression is a Boolean expression?

+4
source

In a way, yes you can. If you know that it will return a boolean, you can even make it a little easier:

 if ( isBar("foo") ) { doSomething(); } 
+2
source

This should not be a problem. I also do not see anything wrong with the syntax. To make sure you can catch the return value in a variable and see if this solves your problem. It would also make it easier to check what returned from the function.

+1
source

Yes, you can indicate that it returns a boolean in your example.

0
source

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


All Articles