You might hear some people taling about "Magic Numbers" every so often. I was excited when I heard about them first! Magic Numbers sound like fun. But it's a bad kind of magic.
A Magic Number is a number that you're using, but you're not entirely sure what it's doing. Its effect is "magic". This is a dangerous thing, because there can be unintended effects from Magic Numbers.
Imagine we're trying to center an item on a
Canvas. Assuming it starts in the top left of the screen, we could nudge it down and right until it looks like it's in the center.
In some made up code, this might look like;
const x = 400; const y = 600; drawItem(x,y)
There are two dangers here.
- We dont know it's in the center.
- If the user has a different size browser (eg the
Canvasgets smaller) our item will be too far down or right, and could even leave the
To avoid using a randomly chosen
y value, let's be accurate. We'll assume the item is a 100 unit square.
const itemWidth = 100; // find out the exact dimensions of the canvas const canvasBoundingRect = document.querySelector('canvas').getBoundingClientRect(); const canvasWidth = canvasBoundingRect.width; const canvasHeight = canvasBoundingRect.height; // use the information we now have about the item and canvas to make accurate calculations const x = (canvasWidth / 2) - (itemWidth / 2); const y = (canvasHeight / 2) - (itemWidth / 2); // draw the item in the center drawItem(x,y)
x as the example, we get
CanvasWidth and divide by two. This gives us the exact center of the Canvas. Then, because our item is drawn from the top left corner, we remove half of it's width (
itemWidth), meaning that when it's drawn, it'll be exactly in the center of the screen.
This is a small example, but it's important to look at the numbers in your app and try to understand why they're there. You will develop a kind of "code smell" for these numbers in time.
const itemCount = 5; const leftNudge = 127;
Here you might understand what
itemCount is. It's the amount of things we want to show on the screen. But
leftNudge? I'm not entirely sure what that's for, and 127 doesnt look like a number someone might know intuitively. That
leftNudge variable feels like it might be a Magic Number.
If you enjoyed this article, sign up here to get new articles whisked straight to your inbox!