JavaScript-Newbie is confused: if(event.shiftKey == 57)?

I hope I’m at the right place for this kind of question 😄
I just started learning programming with the Meta-Course on Coursera and after the JavaScript-Part I thought it would be a good idea to review other people’s codes on GitHub to get some feeling and understanding for whole projects.

So now I’m sitting here, spent 2hrs on research and feeling stupid af…
I don’t get this piece of code:

document.addEventListener("keydown", function (event) {
  if (event.shiftKey == 57) {
    event.key = "(";

afaik shiftKey always returns a boolean value – so how this one can work? (And yes it really does).
Can anyone explain that to me pls?😄

Tried to google it for over 2hrs now.

>Solution :

Short answer: It doesn’t work, it’s a bug

Since, as you pointed out, shiftKey always returns a boolean value, the expression (event.shiftKey == 57) will always be false, looking at the code around it on GitHub:

if (event.shiftKey == 57) {
    event.key = "(";
} else if (event.shiftKey == 48) {
    event.key = ")";
} else if (event.shiftKey == 53) {
    event.key = "%";

We can see that the developer essentially tried to implement the shift key functionality himself. (Note that 57 is the ascii value of the 9 character and 48 of 0) You don’t have to do this, the browser already takes care of it for you.

It’s essentially just a bug, a pretty harmless one since the code is never triggered and nothing is lost here. You could easily imagine how a developer might mistakenly write this code and then test the shift key behavior and assume that since the shift key works his code must be working too.

I think this is a really good catch for a new developer though! If you’re feeling up to it you could open an issue or a pull request ;).

Leave a Reply