jeudi 21 septembre 2017

boolean set to false; returns true on if statement without ==

I have an angular component that has a copmonent-level boolean variable and an onClick event. The html file looks like this:

<div class="divClass" (click)="onClick($event)"></div>

The relevent code from the ts file is as following:

export class myComponent implements OnInit {

  guardFirst : boolean;
  guardSecond : Boolean;

  constructor(...) {
    self.guardFirst = false;
    self.guardSecond = false;
  }

  onClick( ev : MouseEvent ) {

    if (self.guardFirst) {
      if (self.guardSecond) {
        console.log("...");
        // the logic takes place here
      }
      self.guardSecond = true;
    }
    self.guardFirst = true;
  }

}

Ive changed the actual code obviously because it is proprietary, but the structure is the same. You'd expect the logic and the console logging not to occur until the third click in the div, however it occurs on the first. The console logs false for both variables, but has somehow passed the two if statements to get there that, based on the way other languages work, one would expect to return false. After a lot of debugging and console logging to check values and flows, I eventually thought to change the code like this:

onClick( ev : MouseEvent ) {

  if (self.guardFirst == true) {
    if (self.guardSecond == true) {
      console.log("first guard: " + self.guardFirst + "; second guard: " + self.guardSecond);
      // the logic takes place here
    }
    self.guardSecond = true;
  }
  self.guardFirst = true;
}

This tells me that the booleans without a value equivalency statement are returning true whenever they are not null or undefined; false or true, as long as there is a value assigned, returns true. Since my code had booleans as both a primitive AND an object, that is not the reason for this behavior. I tried testing something similar on jsfiddle in Typescript without Angular, and it worked the way I'd expect (returning false if the value was false, regardless of the lack of an ==).

Can anyone explain this phenomenon to me? Where does it come from? It seems like it must be an Angular thing - is that true? Does this always work this way in Angular, or is something off with my project? Is this the intended behavior? If so, why did the developers make that decision? If not, why is it happening?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire