Thomas Clowes
Thomas Clowes

Reputation: 4609

javascript function call in conditional not being called if first returns false

My problem is a seemingly simple one.

I have two functions, function_a() and function_b() which show/hide a div, and return boolean values.

I have a conditional

if(function_a() && function_b())
{
     //do stuff
}

However if function_a() returns false, function_b() is seemingly not executed at all. I however want them both to run because i want them to show/hide their respective divs.

Why does the second function not run if the first returns false, and how do i achieve what i want?

Thanks

Upvotes: 1

Views: 2591

Answers (2)

NullPointerException
NullPointerException

Reputation: 3814

The second function will never get executed if first condition is false because you have && condition. That is how && works.

&& is logical operator and evaluates the left side of the operation, if it's true, it continues and evaluates the right side other wise it will stop and return false.

if you want to execute both then store the return value in some variable and then put the logic

var a  = function_a();
var b  = function_b();

if(a && b){
 //do your stuff
}

Upvotes: 5

Kevin Boucher
Kevin Boucher

Reputation: 16685

You will need to assign them to variables before testing 'truthiness':

var a = function_a(),
    b = function_b();

if(a && b)
{
 //do stuff
}

This way they are both run and then the if statement can check for true/false.

Upvotes: 3

Related Questions