Ruud Schroën
Ruud Schroën

Reputation: 113

`else if` is never executed; only the preceding `if` is executed

I have a function which runs through some <div>s, and inside each <div> it counts the amount of children. Then, based on the amount of children (var length), it does something.

$('.member-type').each(function() {
  var length = $(this).children('.views-row').length;
  
  if (length >= 2) {
    console.log('equal to or more than two');
  }
  else if (length > 5) {
    console.log('more than five');
  }
  else {
    console.log('single item');
  }
});

The first if statement works and the else statement works. But for some reason, the else if statement doesn’t work, even when length is higher than 5 (I checked in the console log).

Does anyone know what I’m doing wrong?

Upvotes: 5

Views: 30963

Answers (3)

Adil
Adil

Reputation: 148110

When the length is greater than 2, it is always greater than 5, so it will always go in the first if statement block. Change the condition in the first if, so that the else part can be executed:

if (length >= 2 && length <= 5) {
  console.log('more than two and less than five');
}
else if (length > 5) {
  console.log('more than five');
}
else {
  console.log('single item');
}

Upvotes: 10

Nick
Nick

Reputation: 2907

If you want both the ifs to work you just remove the else, because the else prevents the second if to be executed:

$('.member-type').each(function() {
   var length = $(this).children('.views-row').length;
   if (length >= 2){
       console.log('equal to or more than two');
   }
   if (length > 5){
       console.log('more than five');
   }
   else{
       console.log('single item');
   }
});

Upvotes: 0

opalenzuela
opalenzuela

Reputation: 3171

Yes. The first if ( length>= 2) includes also the second else if (length > 5)

In another words, if the first condition is met, so is the second, so the flow will never reach the second block.

You can change the code for the following (which, I believe, it's easier to understand):

if (length >5){
   console.log('more than five');
}
else if (length > 2){
    console.log('more than two');
}
else{
   console.log('single item');
}

Upvotes: 5

Related Questions