Give help. Get help.

  • # 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: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: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 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.