Skip to content

JavaScript Conditional Operators

June 2, 2011

One of the most useful feature of coding — programming or scripting — is telling the computer to make decisions. The most common method of doing so is to use an if-else statement. This is rather easy to accomplish, but sometimes having to write out code that makes a simple comparison is just annoying.

var str1 = "apple", str2 = "orange", result;
if (str1 == str2) {
  result = "equal";
}
else {
  result = "not equal";
}

This might be good for beginners, but for those with experience in JavaScript this is a pointless way of coding. This can easily be condensed to one line:

var str1 = "apple", str2 = "orange", result;
result = (str1 == str2) ? "equal" : "not equal";

This odd string of code may look funky from a distance, but will more-than-likely save time, effort, and download time. The question mark separates the values that will be set into result. To the right of the question mark, there are two string literals: “equal” and “not equal.” If the condition (or if str1 equals str2) is true, then result will be given the “true” value (“equal”); else, result will be given the “false” value (“not equal”).

This piece of code can be used in C++, Java, PHP, and other languages. I’ve used this in my programs, and it’s made things easier. Of course, this is just for basic comparisons and not for anything too advanced, like for switches.

And yes, I put semicolons at the end of my statements. That’s the right way to do things.

Advertisements
One Comment
  1. Ternary statements yeah it’s funny how I just learned that a few days ago and here you go posting it. What a coincidence!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: