
Variables are the basic building blocks of JavaScript. In this article, we will learn what variables are, how to use them, and different ways to declare them.
What is a Variable?
A variable is like a name given to a value (data). It helps us to reuse, update, or keep track of its value. In simple words, we need variables to store the data in the memory so that we can reuse them whenever we want. To create variables, we need to declare them.
How to Declare Variables in JavaScript?
Type the keyword let followed by the variable name. You can write any name:
<script>
let userName;
let userAge;
</script>
In the above code, we have declared two variables – userName and userAge. We haven’t assigned any value (or data) to them. So, if we print them, we get undefined.
<script>
let userName;
let userAge;
console.log(userName); // prints undefined
console.log(userAge); // prints undefined
</script>
To assign the data to the variables, we need to initialize them.
Variable Initialization:
Type the variable name, followed by an equals sign (=), followed by the value.
userName = "cool_guy";
userAge = 25;
Now, whenever we need cool_guy and 25, we can use userName and userAge respectively. Let’s print them.
<script>
let userName;
let userAge;
userName = "cool_guy";
userAge = "25";
console.log(userName); // prints cool_guy
console.log(userAge); // prints 25
</script>
You can also declare and initialize variables at the same time:
let userName = 'cool_guy';
let userAge = 25;
Note: You often hear the word identifier in error messages. An identifier is nothing but a variable name. In the above code, userName and userAge are identifiers.
The best thing about variables is that we can update them with a new value.
<script>
let userEmail = "[email protected]";
console.log(userEmail); // prints [email protected]
userEmail = "[email protected]";
console.log(userEmail); // prints [email protected]
</script>
Variable Naming Rules and Conventions:
There are some rules and conventions we should follow while naming variables:
1. Use only Latin characters (0-9, a-z, A-Z), underscore, and $.
2. Do not use numbers at the beginning. If you do this, you will get an error.
Example:
<script>
let 1fruit = 'Mango'; // Uncaught SyntaxError
</script>
3. Do not use underscores at the beginning of the variable names. You won’t get an error, but some JavaScript constructors use underscore at the start and it may lead to confusion.
4. Do not use reserved keywords. For example, don’t name a variable let, for, function, etc…
5. It is recommended to follow the “lower camel case” convention. Write the first word in lower case and capitalize the first letter of the following words.
Examples: userDataLimit, numberOfItemsInCart, itemPrice, searchQuery, etc.
5. Variable names are case sensitive which means small a is not the same as capital A.
Example: userName, UserName, USERname – all are different variables.
6. Variable names should describe what they store. For example, in the above code, we have created userEmail to store the user’s email id. When someone looks at the userEmail, they understand that it stores the email id.
Data Types in JavaScript:
Data type represents the type of data. For example, numbers, text, and decimal values. In JavaScript, you don’t need to declare variable types.
Numbers:
You can store integer values (like 10) and decimal values (like 10.3).
let searchQueriesLimit = 100 // integer
let dataInMB = 10.2 // decimal
Strings:
A string is nothing but a text. You should wrap it in single or double quotes.
let browserName = "Chrome";
let websiteName = 'SemicolonSpace';
Note: Anything you put inside the quotes is a string. For example:
let num1 = '100'; // this is string, not number
Here 100 is a string because we put it in single quotes.
Booleans:
Booleans are true/false values.
let isPremiumUser = true;
let isProfileLocked = false;
Array:
In programming, an array is a collection of elements. We can store multiple values in the array. To create an array, write the values separated by commas and put them in square brackets.
Example:
let usersList = ["Emma", "Sophia", "Olivia", "Steven"];
Object:
Objects are used to store more complex entities.
Example:
let user1 = { name: "Steven", age: 25, email: "abc@gmail" };
We can get the details using the dot operator.
user1.name
user1.age
Code:
<script>
let user1 = { name: "Steven", age: 25, email: "abc@gmail" };
console.log(user1.name); // prints Steven
console.log(user1.age); // prints 25
</script>
Primitive and Derived Data Types:
Data types are divided into two groups – primitive and derived.
Primitive data types are built-in data types. numbers, boolean, and strings are primitive data types.
Derived data types are derived from the primitive data types. Arrays and Objects are derived data types.
typeof Operator:
It is used to print the data type of a variable.
<script>
let num1 = '100';
let numberOfDaysLeft = 9;
let usersList = ['Steve', "Emma"];
console.log(typeof num1); // prints string
console.log(typeof numberOfDaysLeft); // prints number
console.log(typeof usersList); // prints object
</script>
You probably thinking why the userList is an object, instead of an array. This is because in JavaScript all the derived data types come under the object. Since the array is a derived data type, it is an object.
const Keyword in JavaScript:
The const keyword is used to create constant values. They are the same as the variables but once we create them, we cannot update or change them.
Example:
const PI = 3.14;
Note: You should initialize constants when you declare them.
<script>
const PI = 3.14;
console.log(PI); // prints 3.14
PI = 20; // Uncaught TypeError
</script>
Note: Although you cannot update the const variables, you can update the properties of a const object.
<script>
const userDetails = { "name": "Michelle", "email": "[email protected]"};
userDetails.email = "[email protected]"; // updating property
console.log(userDetails.email); // prints [email protected]
userDetails = {"name": "Steve"}; // Uncaught TypeError
</script>
The let and const are the preferred keywords for creating variables in JavaScript. But, when to use what? If you think you will never change the value, use const. Otherwise, go for let.
There is also another keyword called var for declaring variables. It has many disadvantages and is error-prone. Most of the developers are not using it. But, if you go to an interview, they may ask about var. So, let’s look at it.
var is similar to let. We can update it later, but we can also re-declare it.
Example:
<script>
var fruitName = "Apple";
var fruitName = "Mango";
console.log(fruitName); // prints Mango
</script>
The program runs without any error. This is the problem with var. You may declare fruitName at the beginning of the code, and after writing like 100 lines, you may forget it and create a new variable with the same name. If you do this, you lose the first value ‘Apple’. This is the reason var is not used anymore.
let variables cannot be re-declared. If we replace var with let in the above code, it throws an error:
<script>
let fruitName = "Apple";
let fruitName = "Mango"; // Uncaught SyntaxError
</script>
This is why let is preferred for variables. This is also true with const. We cannot re-declare const variables.
Here is the table that shows the difference between var, let, and const:

Related: