vendredi 15 janvier 2021

Why sometimes logical operator && doesn't work and I need to use if statement instead?

I recently realised that sometimes my logical conditional doesn't work in the way that I wanted. For instance, my intention was to run some instruction about if some property is true:

this.property && obj.instruction() // instruction is running as a result of logical statment 

And it works in most cases, but sometimes instead of running function it's returning true:

this.property && obj.instruction() // returns true

It's quite easy to refactor code to work in the way that it is suppose to work:

if (this.property) {
   obj.instruction()
}

So my question is why does JavaScript sometimes behave like this?

Aucun commentaire:

Enregistrer un commentaire