Java Reference
In-Depth Information
To start with, you define a function
checkCharType()
. You start this function by declaring the
variable
returnValue
and initializing it to the character
"O"
to indicate it's some other character than a
lowercase letter, uppercase letter, or numerical character:
function checkCharType(charToCheck) {
var returnValue = "O";
You use this variable as the value to be returned at the end of the function, indicating the type of
character. It will take the values
U
for uppercase,
L
for lowercase,
N
for number, and
O
for other.
The next line in the function uses the
charCodeAt()
method to get the character code of the first
character in the string stored in
charToCheck
, which is the function's only parameter. The character
code is stored in the variable
charCode
:
var charCode = charToCheck.charCodeAt(0);
In the following lines, you have a series of
if
statements, which check within what range of values the
character code falls. You know that if it falls between the character codes for A and Z, it's uppercase,
and so you assign the variable
returnValue
the value
U
. If the character code falls between the
character codes for a and z, it's lowercase, and so you assign the value
L
to the variable
returnValue
.
If the character code falls between the character codes for 0 and 9, it's a number, and you assign the
value
N
to the variable
returnValue
. If the value falls into none of these ranges, the variable retains its
initialization value of
O
for other, and you don't have to do anything.
if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)) {
returnValue = "U";
} else if (charCode >= "a".charCodeAt(0) &&
charCode <= "z".charCodeAt(0)) {
returnValue = "L";
} else if (charCode >= "0".charCodeAt(0) &&
charCode <= "9".charCodeAt(0)) {
returnValue = "N";
}
This probably seems a bit weird at first, so let's see what JavaScript is doing with your code. When you
write
"A".charCodeAt(0)
it appears that you are trying to use a method of the
String
object on a string literal, which is the
same as a primitive string in that it's just characters and not an object. However, JavaScript realizes
what you are doing and does the necessary conversion of literal character
"A"
into a temporary
String
object 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 finished, 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 first (and, in this string, the only) character's code is returned to you. For example,
"A".charCodeAt(0)
will return the number
65
.