Grow your CSS skills. Land your dream job.

Testing for not true vs true

  • # November 12, 2012 at 10:04 am

    I was told once a long time ago in a classroom far, far away that testing for true was a bit more efficient than testing for not true (!$some_var).

    Just curious if this is true, or if anyone even has this in the back of their mind when creating their code structure.

    It has, for some reason, stuck with me. I will often test for true rather than not-true if at all possible.
    I have a feeling I will be face-palming myself soon haha

    # November 12, 2012 at 10:12 am

    In PHP I’m not really sure if it makes a difference in real terms. Ultimately it’s a 1 or a 0 if you get what I mean so I doubt it has a noticeable impact if any at all.

    # November 12, 2012 at 10:14 am

    I think it’s because some stuff might have a default value of false, so if you test for true you’re really sure it’s true because it has to be..if it makes sense…

    # November 12, 2012 at 1:14 pm

    JoniGuiro, if you are referring to testing as such I know what you mean: $somevar === FALSE

    (PS… awesome avatar haha)

    I think it was explained to me that it’s a bit of a double-test… ‘is it not-true?’. Compared to just ‘is it true?’. So if possible, test for true, rather than not-true.

    I highly doubt it makes any difference (noticeably) at all. I was just curious if anyone else had this strange logic in their head ;)

    # November 12, 2012 at 1:21 pm

    I say we run a test case… Let’s loop through 10,000 if statements testing true rather then false. If im bored enough, i just might do it..

    # November 12, 2012 at 1:34 pm

    @fooman, that’s right, it’s a double test.

    Let’s say `$somevar = false`. If you do:

    if( $somevar === false )

    …what you’re really writing is

    if( false === false )

    So you can just do

    if( !$somevar )

    You’ll see this a lot in JS where people are checking something:

    Another reason you’ll want to use `!` is because it checks for more than just `false`. You may be looking through an array looking for a value and it could return:

    • null
    • undefined
    • empty string

    None of those things === false, so you wouldn’t be able to catch them. If you used `!$somevar` then you are golden!

    # November 12, 2012 at 1:35 pm

    And I’ve just realized you were asking for the difference simply between checking true/false. So you’ll just have to take my post above as extra information haha.

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".