JavaScript: Choosing a variable name
Imagine we have a program like this:
const x = 'Father!';
console.log(x);Technically, everything works. We've already seen similar examples, but here we use a variable named x. Bad names make code hard to read and understand. Here are a few examples of poor variables:
const a = 'John';
const n = 42;
const ddr = 'New York';What are these variables? What do they store? To figure this out, you have to read all the surrounding code and guess from the context.
The computer doesn't care what a variable is called. To it, x, abc, message, or elephantInTheRoom are just labels for storing data. People care about other things. Programmers read code far more often than they write it. That's why variable names are an important part of communicating through code.
Good examples
const userName = 'Arya Stark';
const unpaidOrdersCount = 3;
const maxAttempts = 5;A good variable name helps you understand what the program does without reading every line. It's especially important to choose names whose meaning is clear without context, without having to read all the code around them.
Here are a few tips:
- Use English. It's the international standard. It's better to write
ordersCountinstead ofkolvoZakazov. If English is still difficult for you, use a translator, that's fine. Over time it will get easier. - Try to make the name reflect the meaning of the variable. Let it be a bit longer, but understandable.
- Don't be afraid to spend time choosing a good name. It's an investment in the readability and maintainability of the code.
Programmers even have a joke: "Some of the hardest problems in programming are caching and naming variables." Sometimes coming up with a fitting name really is hard. Here's an example: how would you name a variable that stores the number of unpaid orders from customers with outstanding debt from the previous quarter?
And now a small exercise: come up with a name for a variable that will store "the number of the king's brothers and sisters". Write it down in a notepad or send it to yourself by email. Just the name, without explanations. We'll come back to this task in a few lessons.
Instructions
Create a variable that literally describes "the number of my brothers", and assign it the value 2. Print the contents of the variable. After a successful check, compare your name with the name used in the teacher's solution.
Tips
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('2');
});Teacher's solution will be available in:
20:00
