The name of the variable that we choose must be meaningful to understand, what it represents in the program.
var Price = 100;
Using let and const(ES6)
Creating a variable is known as declaring the variable. Before we use a variable, we need to inform that we want to use it. It requires creating the variable and assigning it a name. To declare a variable we use the var keyword.
- To use a variable we must assign it a name is sometimes called an identifier. In the above example, the variable is called price.
- If the name of the variable contains more than one word. So we use camelCase. It means the first word is all lowercase and any other words have their first letter capitalized.
- For example: var myName;
How to assign value to the variable
Once we have created a variable, We can tell it what information we want to store. It known as assigning value to the variable.
var price= 40;
- Now, we can use the variable by its name “price”. Here we set the value for the price variable. Where possible, a variable’s name should describe the data type of the variable.
- The equals sign(=) is an assignment operator. It says that we are going to assign a value to the variable. We also can use it to update the value given to a variable.
- After declaring a variable, we haven’t assigned the value to the variable. Technically it has the value of undefined.
We also can re-create the variable without changing its value. For example, if we re-declare myAge will still have the same value 24 after execution of these statements.
Rules for naming variables
Here are some rules we must follow when assigning a variable name:
- The name of the variable can contain a letter, digits, underscore(_), and dollar sign($).
- They must begin with a letter, not with a digit.
- Uppercase and Lowercase are distinct. That means the variable Total is not the same as total or TOTAl.
- It should not be a keyword.
- White space does also not allow.
- Variable can be any length.
How to define constant in java?