Java Reference
In-Depth Information
Finally, you come to the end of the function and return the
returnValue
variable to where the function
was called:
return returnValue;
}
You might wonder why you bother using the variable
returnValue
at all, instead of just returning its
value. For example, you could write the code as follows:
if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)) {
return "U";
} else if (charCode >= "a".charCodeAt(0) &&
charCode <= "z".charCodeAt(0)) {
return "L";
} else if (charCode >= "0".charCodeAt(0) &&
charCode <= "9".charCodeAt(0)) {
return "N";
}
Â
return "O";
This would work fine, so why not do it this way? The disadvantage of this way is that it's difficult to
follow the flow of execution of the function, which is not that bad in a small function like this, but
can get tricky in bigger functions. With the original code you always know exactly where the function
execution stops: It stops at the end with the only
return
statement. The version of the function just
shown finishes when any of the
return
statements is reached, so there are four possible places where
the function might end.
The next chunk of code checks that the function works. You first use the variable
myString
, initialized
to
"Hello World!"
or whatever the user enters into the prompt box, as your test string.
var myString = prompt("Enter some text", "Hello World!");
Next, the
switch
statement uses the
checkCharType()
function that you defined earlier in its
comparison expression. Depending on what is returned by the function, one of the
case
statements will
execute and let the user know what the character type was:
switch (checkCharType(myString)) {
case "U":
document.write("First character was upper case");
break;
case "L":
document.write("First character was lower case");
break;
case "N":
document.write("First character was a number");
break;
default:
document.write("First character was not a character or a number");
}