1. Technology

JavaScript Making Decisions

10. A Shorter IF Statement

By

Javascript code
Tor Lindqvist/E+/Getty Images

JavaScript provides us with an alternative way of writing an if statement where both the true and false conditions are just assigning different values to the same variable.

Let's start with a simple example as we had back in the fifth part of this tutorial series where we had a message being set to one of two different values depending on whether name is equal to "Stephen" or not. JavaScript allows us to write if statements like this one a much shorter way (although it is not as easy to read unless you understand what it means).

This shorter way gets rid of the keyword if as well as the braces around the blocks (which are optional for single statements). We also move the value that we are setting in both the true and false conditions to the front of our single statement and embed this new style of if statement into the statement itself. The code that we use is:


variable = (condition) ? true-value : false-value;

So our if statement from before could be written all in the one line as:


message = ('Stephen' === name) ?
"Welcome back Stephen" : "Welcome " + name;

As far as JavaScript is concerned this one statement is identical to the longer code:


if ('Stephen' === name) {
    message = "Welcome back Stephen";
} else {
    message = "Welcome " + name;
}

The only difference is that writing the statement this way actually provides JavaScript with more information about what the if statement is doing. The code can run more efficiently than if we wrote it the longer and more readable way.

This way of coding an if statement can dramatically shorten code such as we had in our nested if tutorial. The following example shows how to assign one of five possible values to a single variable using just one statement that incorporates all of the conditions into one statement using this alternative notation.


var answer = (a == b) ? ((a == c) ? "all are equal" :
 "a and b are equal") : (a == c) ? "a and c are equal" : (b == c) ?
 "b and c are equal" : "all are different";

Note that this notation can only be used where all of the different conditions that are being tested are selecting different values to be assigned to the same variable.

You will often use if statements where there are multiple statements within one or more of the blocks or where the values being set in different blocks are not the same variable This notation cannot be used in those situations.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 2. Decision Making
  7. JavaScript A Shorter IF Statement

©2014 About.com. All rights reserved.