- An online shop – the information might include goods being sold and a shopping cart.
- A chat application – the information might include users, messages, and much more.
Variables are used to store this information.
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.
The statement below creates (in other words: declares or defines) a variable with the name “message”:
Now, we can put some data into it by using the assignment operator
let message; message = 'Hello'; // store the string
The string is now saved into the memory area associated with the variable. We can access it using the variable name:
To be concise, we can combine the variable declaration and assignment into a single line:
We can also declare multiple variables in one line:
let user = 'John', age = 25, message = 'Hello';
That might seem shorter, but we don’t recommend it. For the sake of better readability, please use a single line per variable.
The multiline variant is a bit longer, but easier to read:
let user = 'John'; let age = 25; let message = 'Hello';
Some people also define multiple variables in this multiline style:
let user = 'John', age = 25, message = 'Hello';
…Or even in the “comma-first” style:
let user = 'John' , age = 25 , message = 'Hello';
Technically, all these variants do the same thing. So, it’s a matter of personal taste and aesthetics.
In older scripts, you may also find another keyword:
var instead of
var message = 'Hello';
var keyword is almost the same as
let. It also declares a variable, but in a slightly different, “old-school” way.
There are subtle differences between
var, but they do not matter for us yet. We’ll cover them in detail in the chapter The old "var".
We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it.
For instance, the variable
message can be imagined as a box labeled
"message" with the value
"Hello!" in it:
We can put any value in the box.
We can also change it as many times as we want:
When the value is changed, the old data is removed from the variable:
We can also declare two variables and copy data from one into the other.
In such languages, once the value is stored “in the box”, it’s there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can’t reuse the old one.
Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if you’re not planning to use it soon) is recommended to broaden the mind.
- The name must contain only letters, digits, or the symbols
- The first character must not be a digit.
Examples of valid names:
let userName; let test123;
When the name contains multiple words, camelCase is commonly used. That is: words go one after another, each word starting with a capital letter:
What’s interesting – the dollar sign
'$' and the underscore
'_' can also be used in names. They are regular symbols, just like letters, without any special meaning.
These names are valid:
Examples of incorrect variable names:
let 1a; // cannot start with a digit let my-name; // hyphens '-' aren't allowed in the name
AppLE are two different variables.
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
let имя = '...'; let 我 = '...';
Technically, there is no error here, such names are allowed, but there is an international tradition to use English in variable names. Even if we’re writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
There is a list of reserved words, which cannot be used as variable names because they are used by the language itself.
function are reserved.
The code below gives a syntax error:
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using
let. This still works now if we don’t put
use strict in our scripts to maintain compatibility with old scripts.
This is a bad practice and would cause an error in strict mode:
"use strict"; num = 5; // error: num is not defined
To declare a constant (unchanging) variable, use
const instead of
const myBirthday = '18.04.1982';
Variables declared using
const are called “constants”. They cannot be changed. An attempt to do so would cause an error:
When a programmer is sure that a variable will never change, they can declare it with
const to guarantee and clearly communicate that fact to everyone.
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.
Such constants are named using capital letters and underscores.
COLOR_ORANGEis much easier to remember than
- It is much easier to mistype
- When reading the code,
COLOR_ORANGEis much more meaningful than
When should we use capitals for a constant and when should we name it normally? Let’s make that clear.
Being a “constant” just means that a variable’s value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are calculated in run-time, during the execution, but do not change after their initial assignment.
const pageLoadTime = /* time taken by a webpage to load */;
The value of
pageLoadTime is not known prior to the page load, so it’s named normally. But it’s still a constant because it doesn’t change after assignment.
In other words, capital-named constants are only used as aliases for “hard-coded” values.
Talking about variables, there’s one more extremely important thing.
Please name your variables sensibly. Take time to think about this.
Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code was written by a beginner versus an experienced developer.
In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it’s much easier to find information that is well-labeled. Or, in other words, when the variables have good names.
Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.
Some good-to-follow rules are:
- Use human-readable names like
- Stay away from abbreviations or short names like
c, unless you really know what you’re doing.
- Make names maximally descriptive and concise. Examples of bad names are
value. Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
- Agree on terms within your team and in your own mind. If a site visitor is called a “user” then we should name related variables
Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
As a result, their variables are like boxes into which people throw different things without changing their stickers. What’s inside the box now? Who knows? We need to come closer and check.
Such programmers save a little bit on variable declaration but lose ten times more on debugging.
An extra variable is good, not evil.
We can declare variables to store data by using the
let– is a modern variable declaration. The code must be in strict mode to use
letin Chrome (V8).
var– is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover subtle differences from
letin the chapter The old "var", just in case you need them.
const– is like
let, but the value of the variable can’t be changed.
Variables should be named in a way that allows us to easily understand what’s inside them.