最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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

Share Improve this question asked May 23, 2013 at 19:56 Thomas ClowesThomas Clowes 4,61910 gold badges44 silver badges73 bronze badges 1
  • 1 By the way, that's called short-circuiting: developer.mozilla/en-US/docs/JavaScript/Reference/Operators/… – Ian Commented May 23, 2013 at 19:59
Add a ment  | 

2 Answers 2

Reset to default 5

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
}

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.

发布评论

评论列表(0)

  1. 暂无评论