0

I got this code that works perfectly fine, just like i want it to, but then i want to extend it with else if, but the way i have done my code, that's not possible. Feel free to link some good site to learn from.

if(wallLeft < marioLeft && wallLeftWidth > marioLeft)
{    

}
else
{
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
}

//else if(wallLeftWidth < marioLeft && wallLeftWidth > marioLeftWidth)
{   }
else
{ //some code }
5
  • else-if should come before else Commented Jan 19, 2014 at 20:05
  • writing with formatting like: if(something){}else{ makes code look terrible. Commented Jan 19, 2014 at 20:06
  • Why do keep reversing the statements, just swap the operators instead Commented Jan 19, 2014 at 20:06
  • else { ..... statement should be at last... Commented Jan 19, 2014 at 20:12
  • The syntax is if...else if...else. You can have as many else if as you want, but there can only be one else statement at the very end. There are JavaScript reference guides where you can read about the basic syntax: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 19, 2014 at 20:13

2 Answers 2

1

Inverse your conditions, writing if(...){}else{...} looks horrible and is really bad practice. Additionally the order is if, else if, else, you cant use else if after else.

if( wallLeft > marioLeft || wallLeftWidth < marioLeft ) {
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
} else if( wallLeftWidth > marioLeft || wallLeftWidth < marioLeftWidth) {
    //some code 
}
Sign up to request clarification or add additional context in comments.

1 Comment

That works nice! will accept your answer when i can, (6 minutes)
0

Your code is wrong. Try this;

if (wallLeft < marioLeft && wallLeftWidth > marioLeft) {
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
} else if (wallLeftWidth < marioLeft && wallLeftWidth > marioLeftWidth) { 
    //some code 
}

2 Comments

But the code inside the first if-statement i only want to call when the if is false
If it is false, it does not enter in first if statement

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.