DEV Community

Discussion on: Avoid. Magic. Numbers

Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

I mean, I agree, but the example isn't a good one as really if you are going to use keyCode (which is deprecated by the way) then what is wrong with:

check(e) {
    if (e.keyCode === 13) { //13 is Enter Key
      this.attemptSendMessage(e);
    }
  }
Enter fullscreen mode Exit fullscreen mode

No memory assignment, no extra bytes in compiled code as comments are removed, readable by a human and no having to name it in the first place.

There is decent support for .key so you could use that and make it even easier!

check(e) {
    if (e.key == "Enter") {
      this.attemptSendMessage(e);
    }
  }
Enter fullscreen mode Exit fullscreen mode

Instead magic numbers are things like if you have a function and it has numeric values used for loops etc. it is better to define them at the top:

e.g.

function dealCards(){
   for(x = 0; x < 52, x++){
     //deal card;
  }
}
Enter fullscreen mode Exit fullscreen mode

Would be better as the following as it is easy to understand what "52" is!

function dealCards(){
   var deckSize = 52;
   for(x = 0; x < deckSize, x++){
     //deal card;
  }
}
Enter fullscreen mode Exit fullscreen mode

And even better in ES6 if you aren't stuck in the dark ages like me due to IE9 support 😁

Collapse
 
rockwell profile image
Ahmad khattab • Edited

This is same thing, if you're using key then this case is already covered for you by the browser. Then you're good to go!. I was aware of the code thing. But you're correct. I have also added it to the post, huge thanks for pointing this out!.

Collapse
 
grahamthedev profile image
GrahamTheDev

Added an example that is more in keeping with magic numbers and the sentiment of your post as I do agree, they are evil!

Collapse
 
rockwell profile image
Ahmad khattab

Greatly agree, this too. Haven't the support for IE stopped? Microsoft has the new Edge as their flagship browser? You guys still are stuck with that monstrosity xD

Collapse
 
grahamthedev profile image
GrahamTheDev

I work in accessibility and there are still a lot of people stuck on IE due to their screen reader etc. so I still support IE9+ (and by support I mean it all works fine but it might be a bit ugly or clunky in places, perfectly accessible but maybe missing a few "bells and whistles" afforded by modern browsers).

If IE11 support hasn't already stop it is due to soon so for most people it isn't a concern!