Using the if statement effectively

Jake Howlett, 29 January 2001

Category: JavaScript; Keywords: if else case conditional

"If" is probably the most used JavaScript statement in any one given function or script. There are a variation of ways it can be used and your choice of which method can make your coding a lot easier.

The most common use is probably as an if/else statement:

if (passed == true) {
return alert('You passed!')
} else {
return alert('You failed!')
}


However, there is a much simpler method of writing this same code. Using a conditional operator (?:), you can write the above in one line:

return alert( (passed == true) ? 'You passed!' : 'You failed!' )


You could use this in all sort of situations that will help simplify long and complicated functions. For example, say your function defines variables depending on choices made in the document. In the script below the drop-down called "country" has two entries, "England" and "France", in that order. The variable called "Capital" depends on this choice.

function WhatIsTheCapital(){
f = document.forms[0];
Capital = (f.country.selectedIndex == 0) ? 'London' : 'Paris';
alert('The capital of ' + f.country.options[f.country.selectedIndex].text + ' is ' + Capital);
}


Test this out by selecting another value:



Another timesaver when writing if statements is omitting the curly brackets {} when there is only one statement following the "if". For example, this:

if ( needVariable1 ){
variable1 = "this"
}
variable2 = "that";
variable3 = "another";


could simply be this:

if ( needVariable1 ) variable1 = "this";
variable2 = "that";
variable3 = "another";


Obviously, your code will still work whichever method you choose to use. However, the methods described above can save time and make your code less complicated for other developers. QED.