What is a variable?
A variable, in terms of a programming language can be considered a reserved space booked by a developer within the memory of the system in which a particular program is run. These are like containers where we can put values upfront, like at the time of declaration, or we can just let the computer know of their existence and fill those containers or reserved spaces with some value at a later point of time.
Talk is cheap, show me the code — Linus Torvalds
We can think of variables as small containers for various items that we use, on daily basis, in our kitchen, like a container for sugar or salt etc. We usually buy a 1kg or 2kg pack of sugar or salt from the market but we store a certain quantity of sugar or salt in a small jar that is easily accessible for day to day use. This similar concept applies to variables in programming languages.
In a programming language, we can store a particular value in variable, like a number or a string or a boolean, or an array or a function or an object. Basically, we can store all forms data structures within a variable in a programming language. The use-case of storing values in a variable could more imagined with the example where you want to write an article and that article is about someone, suppose Mr. X. Suppose that article uses the word Mr. X in 100 different places in that article. Hence, instead of writing the word Mr. X in 100 different places, we can simply write it once in a variable, say personName and use that personName variable 100 different places in the article. That is the most use of variables in a programming language and particularly in JavaScript.
How to use variables in JavaScript?
In JavaScript, we can declare variables in three different ways which are listed below:
- by using the let keyword;
- by using the using the const keyword; or
- by using the var keyword.
Each of the above-mentioned will perform a similar task of storing a value in a variable but the behavior will be different when it comes to re-assigning a value or accessing that variable.
Before going into any further details about variables, let's have a look at examples below to see how we can define an use variables in JavaScript with all of the above keywords:
→ using the "let" keyword
1let firstName = 'John Doe'; 2let age = 28; 3 4console.log(firstName, age); // John Doe 28 5
→ using the "const" keyword
1const firstName = 'John Doe'; 2const age = 28; 3 4console.log(firstName, age); // John Doe 28 5
→ using the "var" keyword
1var firstName = 'John Doe'; 2var age = 28; 3 4console.log(firstName, age); // John Doe 28 5
As you can notice from all of the above examples that pattern of declaring a variable in JavaScript is very similar. The only change in each of the above example is the use different keyword. And that is all about basic usage of variables in JavaScript.
The var keyword has been quite old in the language. It has been the primary method of declaring variables in the language until 2015 when ES6 came out and introduced two new methods for declaring variables in JavaScript programs i.e. let and const. In the current times, it is recommended to use only let and const keywords in a program to declare variables as these are the improved versions of var.
With that said, we can now tackle the basic characteristics of each of these three kinds of variable. Further details about each of them will covered in a later article and a link to that article will included in this article.
The "let" keyword
Variables which are declared with let keyword can be reassigned a different value at a later of time in a program. Suppose that we have assigned a value to 10 to a particular variable declared with let keyword and at a later point in code, we want to change the value of that variable from 10 to 12. That is completely possible with variables declared with let keyword. This can be checked from the below example:
1let papersPassed = 5; 2console.log(papersPassed); 3 4// Now the person took the exam and got passed in 2 more papers. Now 7 papers are passed. 5 6papersPassed = papersPassed + 2; 7console.log(papersPassed); 8
As can be seen from above example, we can change the value papersPassed variable at a later point in our code. However, the other important thing to notice is that when reassigning a value to papersPassed variable later in the code, we did not use the let keyword. This is because let keyword is required to be used when first declaring a variable. When assigning a new value to the same value, we do no use let keyword again. If let keyword is used again for the same variable, JavaScript will think that we are creating a new variable and since the name of this new variable clashes with an already declared variable, JavaScript will throw an error and will not further execute the program.
Since, variables declared with let keyword can be assigned a new value, it is possible that we only declare them initially and then later assign a value. To explain this further, let's have a look at the below example:
1// A student enrolled in college. The number of papers passed would be zero as no exams are yet taken. 2 3let papersPassed; // value will be undefined 4 5// First year exams. Three papers passed. We should not use plus sign here as it then result NaN. 6 7papersPassed = 3; // value will be 3 8 9// Second year exams. Two papers passed. 10 11papersPassed = papersPassed + 2; // value will be 5 12
The "const" keyword
Variables which are declared with const keyword can't be reassigned a different value at a later of time in a program. Suppose that we have assigned a value to 10 to a particular variable declared with const keyword and at a later point in code, we want to change the value of that variable from 10 to 12. That is not possible with variables declared with const keyword. Therefore, const keyword is used, usually, for variables which are not supposed to change like birth year or value of PI. This can be illustrated from the below example:
1const birthYear = 1990; 2console.log(birthYear); 3 4// It is not possible that a person's birth year will be changed unless it was documented incorrectly. In order to correct that we can use the following code. 5 6const updatedBirthYear = 1991; 7console.log(updatedBirthYear); 8
As can be seen from above example, we have not changed the value birthYear variable at a later point in our code but rather used a new variable to rectify the documentation of birth year. Had we reassigned the value of the birthYear, JavaScript would have thrown an error and program will not be further executed. This is the rule for these variable types that a new value can't be assigned to them. Since, we can't reassign a new value to variables declared with const keyword, we can't declare a variable with const keyword without providing a value. It would also result in an error.
The "var" keyword
Variables which are declared with var keyword can be reassigned a different value at a later of time in a program. Suppose that we have assigned a value to 10 to a particular variable declared with var keyword and at a later point in code, we want to change the value of that variable from 10 to 12. That is completely possible with variables declared with var keyword. This can be illustrated from the below example:
1var birthYear = 1990; 2console.log(birthYear); 3 4// Changing the value of the birthYear variable directly 5 6birthYear = 1991; 7console.log(birthYear); 8
As can be seen from above we can reassign the value of a variable declared with var keyword, similar to variables declared with let keyword. Moreover, we can also just initialise these variables without any value and change the value later in the code similar to variables with let keyword. In many ways variables declared with var keyword have somewhat similar functionality as variables declared with let keyword. However, there are some very critical differences between the two, the important one of which is the scoping of the two kinds of variable. This scoping will be discussed in detail in a later article which will be linked to this article.
With that, now you know three different ways in which you can create variables in you JavaScript program. It is highly recommended that always create variables with let and / or const keywords unless the situation demands the use of var keyword which is absolutely rare.
Naming conventions for variables
There are three very popular naming conventions when it comes to naming variables. These are as follows:
- Pascal case - In this convention all words forming a name of a variable starts with uppercase first character like FirstName or LastName or Age.
- Snake case - In this convention all words forming a name of a variable starts with lowercase and are separated by an underscore like first_name or last_name or age.
- Camel case - In this convention all words forming a name of a variable starts with uppercase first character except for the first character of the first word which would be lower case like firstName or lastName or age.
In JavaScript, it is common and usual practice to always use camel case variable naming convention.
Rules for naming variables
There are few very important rules when it comes to naming variables which are listed below.
- A variable name must not start with a number like 2 or 1 or 3 etc.
- A variable name can only contain $ (dollar sign) or an _ (underscore) as special characters. All other special characters are not allowed.
- A variable must not be a reserved keyword in JavaScript like let, const function etc.
- Variable names should be descriptive enough to give reader an idea of the value or data type the variable holds.
Conclusion
The key take away from this article are as follows:
- We can use variables in our program which will help us in reusing the same values at different points in our code.
- There are three keywords with which we can declare variables in JavaScript and these are var, let and const.
- The value assigned to variables declared with let and var keywords can be changed later in the code.
- Variables declared with let and var keywords can be initialised with no value.
- Variables declared with const keywords can not be initialised with no value and the value of these variables can not be changed later in the code.
- Never start a variable with a number.
- Never use special characters in variable names except for $ or _.
- Never name variables which are reserved keywords in JavaScript.
- It is recommended to use camel case convention for naming variables.