Register to get access to free programming courses with interactive exercises

Variables JavaScript fundamentals

Consider this task: we need to print the phrase Father! two times or even five times. You can solve it via brute force:

console.log('Father!');
console.log('Father!');

This will do for the most basic case, but if you use the phrase Father! more often and in different parts of your code, you have to repeat it everywhere. Then you will face even more issues when it turns out that you need to change the phrase. This is a common scenario in development. We have to find all the occurrences of the phrase Father! and make all the required changes. There is one other way to do it. Instead of copying our expression, just create a variable containing this phrase.

let greeting = 'Father!';
console.log(greeting); // => Father!
console.log(greeting); // => Father!

Variable definition

A variable points to data that it stores. It allows you to use the data multiple times without duplicating it. The variable is created and filled with data (initialized) using the statement let greeting = 'Father!'.

The variable name can consist of characters from any valid character set including English letters and numbers as well as _ and $ signs. Note that you can't place a digit at the beginning of a name. Variable names are case-sensitive, which means that hello and heLLo are two different names and thus two distinct variables. Case is really important in JavaScript, so never forget it.

You don't have to initialize the variable with data when declaring it. Sometimes you may want to create a variable and fill it later:

// Declaring a variable
let greeting;

// Usage
console.log(greeting); // undefined

A declared but uninitialized variable contains an undefined value. This is a special value used when nothing is defined.

You can create any number of variables. Large programs contain dozens or hundreds of thousands of variable names:

let greeting1 = 'Father!';
console.log(greeting1);
console.log(greeting1);

let greeting2 = 'Mother!';
console.log(greeting2);
console.log(greeting2);

For the sake of the code analysis, it's common to create variables near the place they are used.

Variable change

The word "variable" itself suggests that it can vary. Indeed, the value of a variable can change throughout your code.

let greeting = 'Father!';
console.log(greeting);
console.log(greeting);

greeting = 'Mother!';
console.log(greeting);
console.log(greeting);

The name remains unchanged, although it stores new data. Note the key difference between declaring a variable and changing it. The let keyword appears only when you create a variable, but when you modify it, you don't use a keyword.

Some errors regarding variables

The order of statements in code with variables is tremendously important. You must declare a variable before using it. Below is an example of a common beginner's mistake:

// Uncaught ReferenceError: greeting is not defined
console.log(greeting);
let greeting = 'Father!';

Running the above program terminates with the error ReferenceError: greeting is not defined. ReferenceError means that the code uses a name (called an identifier) that is not defined. And the error itself explicitly tells you what it is: greeting is not defined. Besides incorrect definition order, there are more common typos in JavaScript, both when using a variable and when declaring it.

Using a properly configured editor can reduce the number of such errors. These kinds of editor highlight names used without being declared and warns about possible problems.

Another common mistake is trying to declare a variable that is already declared:

let greeting = 'Father!';
let greeting = 'Father!';

You can't do that. You have to create a new variable.

Constants

Throughout the module, our sample code has mostly used variables as names (aliases) for particular values, rather than as variables that change their value over time.

let dollarsInEuro = 1.25;
let rublesInDollar = 60;

let dollarsCount = 50 * dollarsInEuro; // 62.5
let rublesCount = dollarsCount * rublesInDollar; // 3750

console.log(rublesCount);

Such names are often called constants in programming, and many languages support constants as a construct. JavaScript is one of those languages, and its coding standards say explicitly that if the value doesn't change, then we are dealing with a constant. Rewrite the example above to make use of constants:

const dollarsInEuro = 1.25;
const rublesInDollar = 60;

const euros = 1000;
const dollars = euros * dollarsInEuro;    // 1250
const rubles = dollars * rublesInDollar; // 75000

console.log(rubles);

The only change here is syntactical: the keyword let has been replaced by const. Now if we try to change any constant, we get an error message. Otherwise, it behaves the same way as a variable.

const pi = 3.14;
pi = 5; // TypeError: Assignment to constant variable

You may be wondering why we need it. Can't we just use variables? Even if we limit ourselves to variables, it won't change the fact that they will often play the role of constants. Moreover, it is possible to write JavaScript code idiomatically without using variables at all. Take a look at the example from the actual Hexlet code. You're unlikely to understand it at this stage, but try counting the number of constants and variables there are, you'll see that there's exactly one variable and a whole bunch of constants.

Constants make it a lot easier to analyze; when we encounter a constant, it's obvious right away that its value always stays the same. With constants, we don't need to worry about when they were written. With variables, however, we can't be certain of their value and have to analyze all the code to figure out how they may have changed.

Variables are essential only in one case (in all others, we can do without them for sure) and that's when we're dealing with loops. We'll get to that point later.

From now on, we will stick to constants and use variables only when it's inevitable.

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY