Using the if statement effectively
"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.
type-o in your code
FYI. . . in the first example when you compare it should be passed == true - as it is you are setting passed equal to true (its wrong in the before and after code)
Reply
Re: type-o in your code
Thanks Joe. Fixed now. Rather embarassed that it was there though ;o)
Jake
Reply
Conditional Statement with Alerts and Function
Just wondering, since I've the following below:
function checkOriginality() { var f = document.forms[0];
if (f.OIIMarks.value != 0) { alert("Part II will be set to 0") f.OIIMarks.value = 0; return false; }
if (f.OIIIMarks.value != 0) { alert("Part III will be set to 0") f.OIIIMarks.value = 0; return false; } }
Can I shorten it by using a conditional statement?
Reply
Re: Conditional Statement with Alerts and Function
Not using this method you can't Charlotte. You've got it just about as short as possible.
Jake
Reply
Show the rest of this thread