Programming Tip Of The Day #1 – Ternary Operator

So, I though I’d start this series called Programming Tip Of The Day to write about useful things I come across in programming.  Both to educate my readers and as a personal archive of ideas and tips.

I will kick it off today with a quick rant about the ternary operator.  I <3 the ternary operator.  It’s quick, efficient and saves a lot of ugly code.

For those of you who don’t know, the ternary operator is made up of 3 elements: The condition and two results.  It is of the form:

(condition) ? (result if true) : (result if false);

This is much nicer than an if statement.  So here is a brief example about how a ternary operator can replace an if-statement.

if-statement

if(isSnowing) {
	iMustBe = "cold";
} else {
	iMustBe = "warm";
}

Same thing using ternary

iMustBe = isSnowing ? "cold" : "warm";

That is so much easier to read (IMHO). You can even do clever things in printing. Here is a small example in PHP for using the ternary operator when doing an echo.

<?php
  echo "I am a ".((height > 72) ? "tall" : "short")." person!";
?>

Most languages support the ternary operator. Check out this wiki page if you want more info.

Happy programming!

Tags: , , , , ,

3 comments

  1. I use the ternary operator ALL the time. It is super elegant and highly useful. The only time it can get really kludgy is if people do nested ternarys. That’s ridiculous.

  2. I totally agree, nested ternaries sound very gross.

  3. I love when I see this:

    if (value == “something”)
    return true
    else
    return false
    end

    Of course, this can be simplified:

    return (value == “something”)

Leave a comment