JavaScript: Magic numbers
Let's look at an example of a program that performs currency conversion:
const eurosCount = 1000;
const dollarsCount = eurosCount * 1.25; // => 1250
const rublesCount = dollarsCount * 60; // => 75000
console.log(rublesCount);Technically, the code works. But from a professional development standpoint, such code is considered bad practice.
What's the problem?
The expressions use unclear numbers: 1.25 and 60. What are these values? An exchange rate? Where did they come from? In a month or a year, you most likely won't remember what these numbers mean. And if another developer opens the code, they simply won't understand where everything comes from. Such numbers are called magic.
Magic numbers are numeric values whose meaning is not clear from the code. They are usually used directly in mathematical expressions, without variables that have meaningful names. To understand their purpose, you have to dig into the context or read additional documentation. Magic numbers make code harder to read, understand, and maintain.
How to avoid the magic
The simplest way is to extract such values into variables with clear names. Then the meaning becomes obvious:
const dollarsPerEuro = 1.25;
const rublesPerDollar = 60;
const eurosCount = 1000;
const dollarsCount = eurosCount * dollarsPerEuro; // => 1250
const rublesCount = dollarsCount * rublesPerDollar; // => 75000
console.log(rublesCount);The numbers themselves haven't gone anywhere, but now they are stored in variables whose names unambiguously tell you what they are.
Conclusion
Magic numbers make code unclear and hard to maintain. To avoid this problem, you should replace such numbers with variables that have meaningful names. This makes the code more readable, especially in the long run. Clear code is always more important than compactness, even if the program becomes a bit longer.
Instructions
There are pallets with boxes in a warehouse. Extract the "magic" numbers 6 and 17 into named variables and print the result.
console.log('Boxes in stock:');
console.log(6 * 17);Expected output:
Boxes in stock:
102Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('Boxes in stock:\n102');
});Teacher's solution will be available in:
20:00
