JavaScript Making Decisions

Formatting an If Statement

There are several different ways that you can format if statement. In my earlier examples I placed the opening brace on the same line after the condition, the closing brace directly under the if, and indented the content. Some people prefer to place both the opening and closing braces on their own lines indented to match with the rest of the content. There are also a number of other alternatives. It is not important which alternative format you use. What is important is that you select one particular format and use that format consistently in all of your code. Writing code in a consistent way makes it easier to read.

It is valid to combine statements together in JavaScript and so you could combine both an assignment of one Boolean variable to another with a test of whether it is true or false for an if statement. Such an if statement could read:

if (ready = standingBy) {. . .

This means that the value in standingBy gets copied to ready and then tested to see if it is true or false in order to determine whether to run the following code or not. There is no comparison performed in this code. The similarity in appearance between the assignment statement in this code and the code used to perform a comparison, can easily lead to confusion when your code does not work as expected due to a difference in the number of equals that you have included. To minimize the chance of confusion in your code as to what an if statement is meant to be doing I recommend that you do not include assignments where comparisons are normally expected.

Where you are comparing a variable with a fixed value (either a number or a text string), you can make it easier to detect if you have accidentally forgotten an = in your if statement by putting the constant value on the left.

if (3 == count)

As constant values can be assigned to variables but variables canít be assigned to constants this will produce a syntax error if one of the equals is omitted by mistake. Were you to code this with the variable on the left then leaving out an = would result in the code performing the wrong test but no error message would be produced.

go to previous section go to next section 

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate