C.Ronaldo
C.Ronaldo

Reputation: 611

else if statement getting ignored

I have a function that has to act different if pan.cost > 0.

So let's say curPos = 3 and pan.cost = -1

Now when I do this, no matter what, if(curPos + 1 === 5 || 30) is always used even if curPos + 1 is 2,3,4,6 etc (as long pan.cost < 0)

Now I have put console.log(curPos + 1) inside the else if-statement and it also says their that it does not meet the requirements.

function action(curPos)
{
  var pan = panel[curPos];

  if(pan.cost > 0)
  {

  }
  else if(curPos + 1 === 5 || 39)
  {
    console.log(curPos + 1);

  }
  else if(curPos + 1 === 3)
  {
    console.log("should be here");

  }
}

Upvotes: -1

Views: 425

Answers (4)

El Duderino
El Duderino

Reputation: 1392

Try this:

function action(curPos)
{
  var pan = panel[curPos];
  var newCurPos = (curPost + 1);

  if(pan.cost > 0)
  {

  }
  else if(newCurPos === 5 || newCurPos === 39)
  {
    console.log(newCurPos);

  }
  else if(newCurPos === 3)
  {
    console.log("should be here");

  }
}

Upvotes: 1

Daniel
Daniel

Reputation: 533

|| 39 will always return true and pan.cost doesn't exist.

Upvotes: 1

Ozan
Ozan

Reputation: 3739

if(curPos + 1 === 5 || 39) will always evaluate to true. Look at the part after your or pipes. if(39) will always be true.

Upvotes: 1

Anna Fohlmeister
Anna Fohlmeister

Reputation: 447

The line

curPos + 1 === 5 || 39

always evaluates to truthy, because it is read:

(curPos + 1 === 5) || 39

and 39 is a truthy value.

Upvotes: 1

Related Questions