skip to Main Content

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.

2

Answers


  1. So keys have ascii values assigned to them and it looks as though this person wants to return a open bracket when someone hits the "9" key (ascii value 57) while pressing shift. What it seems is confusing you is [the difference between == and === in javascript][2], learning about [truthy and falsy][3] values will also probably help you understand what is going on here. However, without any context, I’m unsure this code will do what it intends to do, but I hope these resources will help you understand.

    [2]: https://www.freecodecamp.org/news/loose-vs-strict-equality-in-javascript/#:~:text=The%20%3D%3D%20operator%20performs%20a,well%20as%20the%20same%20value).
    [3]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

    Login or Signup to reply.
  2. 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 ;).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search