2

I have an If statement that runs within a 'for' loop to create markers for a Google map. Basically if a tick box is not ticked it runs the code all displays all markers, but if a checkbox is ticked then it checks for a 2nd parameter and only runs the code for the items that match this condition.

The code I have below works fine, but it means I have to use the same code in both parts of the if statement. Apart from building it into a function if there a better way of structuring the If statement to achieve this?

if(!FriendlyChecked){

    //Code here

} else if(FriendlyChecked && Friendly == "Yes"){

    //Same code here

}
1
  • Your else if condition is redundant. If FriendlyChecked is true (in which case it will go to the else if statement) then why are you checking if FriendlyChecked is true again? Commented Jul 25, 2012 at 13:27

3 Answers 3

9

If FriendlyChecked is false, the first condition is satisfied and the code will be executed.

Thus, if the second condition is reached, FriendlyChecked must be true, so you don't need to check it at all, you only need to check that Friendly == "Yes".

if(!FriendlyChecked || Friendly == "Yes"){
    // code here
}
Sign up to request clarification or add additional context in comments.

Comments

2
if( !FriendlyChecked || (FriendlyChecked && Friendly == "Yes") ) {

  // your code

}

!FriendlyChecked || (FriendlyChecked && Friendly == "Yes") will check for either FriendlyChecked is false (not checked)

OR FriendlyChecked is true an value of Friendly is Yes

1 Comment

Beat me to it by about 3 secs.
0

This will solve your problem

 if((!FriendlyChecked) ||((FriendlyChecked)&&(Friendly == "Yes")){

 //Code here

} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.