This is due to the character 3
's ASCII value (ASCII is a widely-used way for computers to numerically represent various common characters). If you look under the ASCII printable characters section of that Wikipedia article, you'll see that the Glyph (or character) 3
has a Dec value of 51
. You can see the dec values of other common printable characters in that same table.
Remember that when you press the 3 key on your keyboard, the computer is going to see the character 3
, and not a raw integer value of 3
. The Glyph column of that table represents the character value, and the Dec column represents the raw integer value representing that character in the ASCII scheme. You can also see the Binary representation in that table, which is what the Dec integer value breaks down to for how a computer actually handles that value on the lowest level.
In your code, the charCode
variable is being assigned the dec value of the keystroke (via e.which
or e.keyCode
, where e
looks to be the base JavaScript Event
object), which is of type Number
. This is why the switch
further down in the code is comparing charCode
against numerical values.
You can switch between characters and their dec values in JavaScript with the fromCharCode()
and charCodeAt()
functions.