If and else if Statements

From Q
Jump to navigation Jump to search

if statements

An if statement is code which uses a Boolean expression to determine the result. For example,

if (age < 35) 1; else 0

assigns a value of 1 if the value of age is less than 35 or otherwise a value of 0. You must include the word else in the code when writing if, unless using shortcuts, as described below. For example, if you were to write if (1==1) 1; 0, Q will always return a value of 0.

The Boolean expression can be complex, if appropriate. For example,

if (age < 35 || gender == 1) 1; else 0

where || means or. Or,

if (age < 35 || gender == 1 && income > 50000) 1; else 0

Similarly,

if (isNaN(v1) && Math.pow(v2,2) == v3) 1; else v2;

returns a value of 1 if v1 has missing data and v2 squared equals v3, and returns the value of v2 otherwise. See JavaScript Tips for more information about Boolean expressions and associated matters (e.g., how to refer to missing values). Note also that the final statement on a line may or may not end with a semicolon (;).

else if statements

Multiple if statements can be chained together, which is often the most straightforward way of creating categorical variables. For example:

if (age < 35 && gender == 1) 1; //young males
else if (age < 35 && gender == 2) 2; //young females
else if (age >= 35 && gender == 1) 3; //older males
else if (age >= 35 && gender == 2) 4; //older females

It is important not to forget the else on all but the first line, as if forgotten, everything above that line will generally be ignored.

Using braces

We can write the previous example in a slightly different way, to achieve the same outcome:

if (age < 35) {
    if (gender == 1) 1; 
    else 2;
} else {
    if (gender == 1) 3; 
    else 4;
}

Which version is better really depends on what you find more readable.

Short cut if statements

If you are wanting to use if statements to create binary variables, it is only necessary to create the Boolean expression. For example if (age < 35) 1; else 0 is the same as just writing age < 35.

Also, you can write if (age < 35) 17; else 44 as age < 35 ? 17 : 44.

The earlier example involving age and gender can thus be rewritten as:

age < 35 ? (gender == 1 ? 1 : 2) : (gender == 1 ? 3 : 4)

or, to be even more concise:

1 + (age >= 35) * 2 + gender == 2

See also