5
Big-R
8y

Not a rant but a question/style.

What do you prefer and why?:

if(condition)

vs

if (condition == true)

and

if (!condition)

vs

if (condition == false)

vs

if (condition != true)

Comments
  • 7
    In low level languages you may gain a clock cycle with the if(condition)
  • 5
    if(condition) and if(!condition) 🙋
  • 1
    We had a debate which lasted an entire afternoon in our office about this. Started from a code review being talked about on Skype and escalated into a good-natured "discussion" It seemed that everyone who walked past got involved. Some people argued with "=== true" was more readable, others that you ended up with superfluous code.

    Me? Without the ===. Every time. And I'm right.
  • 0
    @njpugh90 I also missed if (condition != true) but no one uses that I think..
    I really don't like if (true == condition) same as if (null == object)

    🤐
  • 0
    @njpugh90 haha, I feel your pain...
  • 2
    i prefer to be as explicit as possible.
    so either cast to bool or ($something === true) or ($something != false) :p
  • 0
    If prefer (condition) and (!condition)

    Although I do make an except for String.IsNullOrWhiteSpace()
    In a conditional I feel the "!" would be overlooked
  • 3
    njpugh90: true==condition is a "yoda condition", it's terrible and should be mocked accordingly
  • 1
    I think if(condition==true/false) is most readable, so I use that!
  • 2
    @Lasse @lotd That's the thing, though. Readability is subjective and very much based on what we're accustomed to. As far as I'm concerned, that completeness just looks odd and distracts me from reading the actual meaning. But I can't tell anyone else what they should find "readable".
  • 0
    I think you should only use == (or === for that matter...) with languages that have truthy and falsy values. undefined and false are different in JS for example, and would both equate to falsy
  • 0
    Always if (condition), but I'll usually store the condition in a variable beforehand for readability. For example:

    Instead of..
    if person.height > 100

    I would do something like..
    let userIsTallEnough = person.height > 100
    if (userIsTallEnough)
  • 3
    Those who write

    if (condition == true)

    should really write

    if (((condition == true) == true) == true)

    just to make it extra clear.
  • 1
    I am lazy, and I find the longer forms... unpleasant.
  • 0
  • 0
    Pretty sure the if(value != true) is bad practice in JavaScript. The answer for this type of question is generally going to be language specific though as you can't do if(!value) in a language like Go
  • 0
    === because PHP. Can't check type otherwise.
Add Comment