Home > Net >  Why foreach loop if else condition always returning true in angular?
Why foreach loop if else condition always returning true in angular?

Time:10-09

I am using a for each loop to loop through each elements in a array so am checking if value is greater than 18 if true am setting a boolean variable to true or else to false. The problem here is it is working fine as i debug but i want to display a div if it returns true or else another div if it returns false but here it is always returning true only. Please find the snippet below

sum = [28,10,15,18,20]

 this.sum.forEach(value => {
    if (value > 18) {
      this.isGreater = true;
     
    }
    else if(value <= 18){
      this.isGreater = false;
    }

  })


 <div *ngIf="isGreater == true">
                    <ul class="c-adv-search__tags" *ngFor="let data of resultList[i].DisplayTags | slice:0:1">
  
                      <li class="c-adv-search__tag"> {{data}}</li>
                 
                    </ul>
                    <ul class="c-adv-search__tags">
                      <li class="c-adv-search__tag number"> {{item[i]-1}}</li>
                    </ul>
                  </div>

CodePudding user response:

The last value in your list is 20, which is greater than 18, so isGreater is set to true.

It's easier to visualize with a traditional for-loop:

let isGreater;
sum = [28,10,15,18,20]

for( let i = 0; i < sum.length; i  ) {
  let value = sum[i];
  if (value > 18) {
    isGreater = true;
     
  } else if(value <= 18) {
    isGreater = false;
  }
}
i value isGreater
0 28 true
1 10 false
2 15 false
3 18 false
4 20 true

So when your loop finishes, your isGreater field is set to true. Last value wins.

If you add a new value at the end, 12, isGreater will always be false, for the same reason. The last value in your array is the last one checked by your loop, so it's the one that will determine the value set on your isGreater variable.

I can't really suggest an alternative design because there's no real way to determine "greater than" across a collection of integers.

CodePudding user response:

The loop is returning:

[true,false,false,false,true]

I don't know where exactly is the issue that you are facing but the loop and if...else condition works fine here. Keep in mind that you are overwriting the same variable with every iteration of the loop.

Since after the last iteration your variable this.isGreater = true; it stays that way after the loop finishes.

  • Related