Tag Archive - shorthand

Ternary Operator – Your Best Friend

If you have never used the Ternary Operator, or ? operator, your life is about to change. The ternary operator is used as a shorthand for if .. else structures that can really clean up your code. Some may want to classify this under a intermediate or advanced skill, but it is so useful that I think it should be included with the most basic tutorials.

Take this for example:

<?
if( $use_live_server ) {
     $url = "http://www.thelivesite.com"
} else {
     $url = "http://www.thedevsite.com";
}
?>

This block of code sets which URL we want to connect to based on if a variable called $use_live_server. While the block of code is perfectly valid, there is a much better way to do the exact same thing in a single line of code.

<?
$url = $use_live_server ? "http://www.thelivesite.com" : "http://www.thedevsite.com";
?>

That one line of code does the exact same thing and once you understand how this works. Here is how the ternary operator works:

<?
$variable = $expression_to_evaulate ? true : false
?>

You do not necessarily have to have a variable that is true or false. You can do any expression you need to.

The jQuery Class

Before we have any major discussion about jQuery it is important that one understand how it works. A lot of your jQuery code will use the jQuery class. You can use the jQuery class two different ways.

jQuery('#dom') – Full text way to use jQuery. You will only use this if the shorthand functionality is already being used by another library.

$('#dom') – Shorthand way to use jQuery. Does the same as above but is significantly shorter.

Very short and quick tutorial but this is one of the most important concepts that you understand in order to be successful with jQuery.