3 Tips for Writing Effective Conditional Statements in JavaScript

Leave a Comment

The example of a nested conditional statement in the last section may look a little scary. There are lots of (), {}, elses, and ifs. And if you happen to mistype one of the crucial pieces of a conditional statement, your script won’t work. There are a few things you can do as you type your JavaScript that can make it easier to work with conditional statements.

#Tips 1.

Type both of the curly braces before you type the code inside them. One of the most common mistakes programmers make is forgetting to add a final brace to a conditional statement. To avoid this mistake, type the condition and the braces first, then type the JavaScript code that executes when the condition is true. For example, start a conditional like this:
if (dayOfWeek=='Friday') {
}

In other words, type the if clause and the first brace, hit Return twice, and then type the last brace. Now that the basic syntax is correct, you can click in the empty line between the braces and add JavaScript.

#Tips 2.

Indent code within braces. You can better visualize the structure of a conditional statement if you indent all of the JavaScript between a pair of braces:
if (a < 10 && a > 1) {
alert("The value " + a + " is between 1 and 10");
}
By using several spaces (or pressing the Tab key) to indent lines within braces, it’s easier to identify which code will run as part of the conditional statement. If you have nested conditional statements, indent each nested statement:
if (a < 10 && a > 1) {
//first level indenting for first conditional
alert("The value " + a + " is between 1 and 10");
if (a==5) {
//second level indenting for 2nd conditional
alert(a + " is half of ten.");
}
}

#Tips 3.

Use == for comparing equals. When checking whether two values are equal, don’t forget to use the equality operator, like this:
if (name == 'Bob') {
A common mistake is to use a single equal sign, like this:
if (name = 'Bob') {
A single equal sign stores a value into a variable, so in this case, the string “Bob” ,would be stored in the variable name. The JavaScript interpreter treats this step as true, so the code following the condition will always run.

0 comments:

Post a Comment