Please enable JavaScript to use CodeHS

CodeHS Glossary


Magic Number JavaScript

A number in your code that appears arbitrary. All magic numbers should all be replaced with calculations or [constants][1]. Having magic numbers in your code is bad programming style. It can also be bad for functionality purposes, so you should avoid using them. It's ok to use simple numbers like 0 or 1 in your code, or even numbers like 2 or 3 in some circumstances. ---------- **An example of using magic numbers and how to fix it.** This code draws a circle in the top middle of the screen. function start() { var circle = new Circle(30); circle.setPosition(200, 30); add(circle); } The magic numbers are `30` and `200`. Here are the steps to take to remove them. If someone else is looking at your code, they might ask, "Why 200?" or "Why 30?" 1. Make a [constant][2] called `RADIUS` that has a value of 30. 2. Use a calculation to find the middle of the screen using `getWidth();` After doing that, the code should look like: var RADIUS = 30; function start() { var circle = new Circle(RADIUS); circle.setPosition(getWidth() / 2, RADIUS); add(circle); } Now, your code is easier to understand. Someone looking at your code won't ask why you're using the number 200, since you used a calculation instead. Additionally, if you want to change the size of the circle, you only have to edit the value of `RADIUS`. Before, you'd have to change `30` to the new value in *two places*. Note that 2 is not a magic number here, since it's clear why you are using it -- to get half of the width. [1]: http://codehs.com/glossary/term/13 [2]: http://codehs.com/glossary/term/13