Get up to 80 % extra points for free! More info:

Lesson 18 - Most common mistakes of JS beginners - Naming variables

In the previous lesson, Strict operators and casting in JavaScript, we focused on casting in JavaScript, learned abbreviated notation of conditions and avoiding many problems using strict operators.

In today's JavaScript tutorial, we will show you the first good programming practices in JavaScript. Not only newcomers often break them and make unnecessary mistakes in their programs, maybe you make them as well?

Word of senior programmer

Congratulations on mastering the first lessons of JavaScript Basics!

I compiled the material for today's lesson based on 20 years of programming experience. As an editor-in-chief and a lecturer, hundreds, maybe thousands of source codes created by the community have passed through my hands. It was not difficult to notice that most of them, although working, contain unnecessary errors, which are also repeated over and over again. Surprisingly, mistakes were often made by both novice and more experienced programmers, and I made them when I started as well.

I have come to the conclusion that the basic and false assumption is:

✗ The program is correct if it works.

Programs and houses

If we build a house that we love and the wind doesn't blow inside, it doesn't mean it's flawless. The house must have a well-thought-out architecture, and if it has no foundations, it will start to collapse in a few years.

Programming is often compared to a construction in terms of architecture, but here, we mean software architecture. Let's explain why.

The human brain can only work with a limited amount of information at a time. Simply put, if a program is cluttered, from a certain point on, the programmer would have to keep more things in mind than one can. Adding additional functions to such a program will always cause an error in the application. In real life, it turns out that the author of a hobby project "stops having fun" or the commercial project goes bankrupt because it is "already too complicated".

Let's take another example - If our household was arranged so that we had a hammer in a first-aid kit which will be placed in the basement, it would probably be difficult for us to function effectively in this kind of household. Although this example sounds absurd, its program alternatives are emerging daily.

When is the program correct?

It is easy. The program is correct if it:

  • works
  • adheres to good practices and
  • is tested.

Note that the functionality from the program user's point of view represents only 1/3 of the program's quality criteria. Like the functionality of the house from the point of view of the occupant, it represents only a fraction of its real quality in terms of construction.

We will be talking about breaking "good practices" and the quality of the code today. We care about you being excellent, so you will find a few more of these lessons across our courses.

How to name variables correctly?

It is said that 10% of the time we program something and 90% of the time we come up with a name for it;-) This is, of course, an exaggeration, but the joke comes across the need to spend some time figuring out the names of the variables. That everyone, including us, who returns to our own code after a few months, understands what the variable is for. In general, you can rely on a simple rule:

We always name variables according to what they contain, not according to what they are used for in the program.

Let's compare the following 2 codes:

✗ False

let list, text2;
let array;
let foo, bar, x, calculation;

✓ Right

let title, name;
let answers;
let i, j, bonus, totalBonus;

Both codes create variables for a simple quiz. In the first example, it is not at all clear what some variables contain, e.g. naming a variable array has about the same meaning as if we would call it a variable.

A common mistake is that we want to save the result of a calculation, for example, and name the variable calculation. However, the calculation is not related to the variable at all, it is an action, the variable always contains a value (the result of the action). This is the case with the totalBonus in the quiz. Similarly, in the first code named variable list because it is being listed somewhere. But we can really see from the second code that it contains the name of the quiz.

Hand on heart - would you understand that the code on the left is a quiz program?

We also never name the variables auxiliary or aux, etc.

Pay attention to "Czechglish" and diacritics

In the source code, at our beginner level, it does not matter in which language we will name the variables (unless we send the code in Czech to an Englishman).

We name variables in one project in one language and, if in Czech, without diacritics!

Let's show some examples again:

✗ False

let zprava = "Hi!";
let count;

✓ Right

let message = "Hi!";
let count;

Or:

let message = "Ahoj!";
let count;

We never use hooks and commas in identifiers (e.g. variable names). Of course, this is already fine in the values stored in them.

Although modern languages support UTF-8 encoding in identifiers, it is very easy to forget a hook or comma and then use another variable ! In addition, the source code file can be processed by an application that does not support it, and this typically happens over time (for example, it is sometimes a problem to display accents in an attachment by a mail client, etc.).

Multi-word variables

Today's applications are increasingly complex. It often happens that one word is not enough to describe what is stored inside a variable. Then it is advantageous to use more words. Short identifiers from the 1980s thus alternate with relatively long names such as userObjectOutputStreamFactory and the like in current business applications.

However, such a long name only makes sense in a complex application, where there are several similar variables, so we have to add another word. So in the Hello world application we will not create the variable textWithAHelloWorldGreeting, but we only need a greeting there, if there is no other:)

Word separation

For the readability, we must somehow separate the words in such a variable name:

  • We separate several words according to the convention of the given programming language, which in JavaScript is called camelCase (where every other word has a capital letter and the name then looks like camel humps). In other languages, for example, an underscore such as snake_case and other notations can be used.
  • If possible, we avoid numbering variables and do not write numbers in words at all, not greeting2 or greetingTwo. "Two" says nothing about what the greeting contains.

Let's look at examples:

✗ False

let message1;
let messageTwo;

It is not clear here what is stored:

let received; // text, bytes, message, order, ...?
let sent;

And here is the name illegible:

let receivedmessage;
let sentmessage;

✓ Right

let receivedMessage;
let sentMessage;

We do not use abbreviations

Let's start this subchapter with the quote:

Everyone was wondering what was the column DATBIR for. Once it was discovered that it was the date of birth.
This bad practice is actually the opposite of multi-word variable names. We do not come up with nonsensical abbreviations, for example, no one knows rm receivedMessage. The aid can be:

If someone other than us looks at the code, they should know exactly what is in the variable.

✗ False

let ms;
let mc;

✓ Right

let message;
let messageCount;

As promised, we will return to the topic of good practices several more times in similar, rather relaxing lessons:)


 

Previous article
Strict operators and casting in JavaScript
All articles in this section
JavaScript Basic Constructs
Article has been written for you by Vlasta
Avatar
User rating:
1 votes
Passionate reader, student, coder and writer.
Activities