Variables are used to store data in a program . Variables are designed to store some temporary data or data that can change its value during operation.
The var and let statements are used to create variables . For example, let’s declare a variable username:
A variable declaration represents a single statement, so it ends with a semicolon.
A similar definition of a variable using the let statement :
Each variable has a name. The name is an arbitrary set of alphanumeric characters, an underscore (_), or a dollar sign ($), and names must not begin with numeric characters. That is, we can use letters, numbers, underscores in the name. However, all other characters are prohibited.
For example, the correct variable names are:
- variablename_number (for example name_2)
The following names are invalid and may not be used:
- Any Variable name starts with number like 2name
await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, yield
var myEmail; var Myemail;
You can define multiple variables separated by commas:
var myEmail, Myemail;
Assigning a value to a variable
Once a variable has been defined, it can be assigned a value. The assignment operator ( = ) is used for this:
var myEmail; var myEmail = "email@example.com";
That is, in this case, the variable myEmail will store the string “Tom”. After assigning a value to a variable, we can do something with this value, for example, print it to the console:
var myEmail; var myEmail = "firstname.lastname@example.org"; console.log(myEmail);
You can immediately assign a value to a variable when you define it:
let phone = "000000"
The process of giving a variable an initial value is called initialization .
The great thing about variables is that we can change their value:
var phone = "123456789"; console.log(phone); var phone = "000000000"; console.log(phone);
The const keyword can be used to define a constant , which, like a variable, holds a value, but the value cannot be changed.
const username = "Tom";
If we try to change its value, we will encounter an error: Uncaught SyntaxError: Identifier ‘username’ has already been declared
const username = "Tom"; const username = "Biswas";
It is also worth noting that since we cannot change the value of a constant, it must be initialized, that is, when defining it, we must provide it with an initial value. If we do not do this, then again we will encounter an error:
When to use variables and when to use constants? If you are sure that the value will not change during the course of the program, then this value is defined as a constant. If it is not known whether the value will change or not, then it is recommended to define the value as a constant. And if you need to change it later, you can simply change the definition of the value from const to var / let .