Java Reference
In-Depth Information
containing “A”. Then, and only then, does JavaScript perform the charCodeAt() method on the
String object it has created in the background. When it has fi nished, the String object is disposed of.
Basically, this is a shorthand way of writing the following:
var myChar = new String(“A”);
myChar.charCodeAt(0);
In either case, the fi rst (and, in this string, the only) character's code is returned to you. For example,
“A”.charCodeAt(0) will return the number 65 .
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 fi ne, so why not do it this way? The disadvantage of this way is that it's diffi cult to fol-
low the fl ow 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 execu-
tion stops: It stops at the end with the only return statement. The version of the function just shown
fi nishes when any of the return statements is reached, so there are four possible places where the func-
tion might end.
In the body of your page, you have some test code to check that the function works. You fi rst 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 defi ned earlier in its com-
parison 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”);
Search WWH ::




Custom Search