The difference between a variable and a constant is this: once you give a value to a constant the value is meant to be kept unchanged throughout the script. In all circumstances where you reasonably foresee that the original value is modified through the script, by all means use a variable as your storage room. In fact, you’re going to use variables most of the times.
In this lesson, you’re going to learn:
- how to create variables and constants;
- how to assign values to variables and constants;
- how to use variables in your code;
- how to name variables and constants correctly.
How to create variables and constants
You declare, that is, create variables and constants in a similar way.
Here’s how you declare a variable:
In the sample code above you declare a variable named amountDue.
The variable declaration ends with a ( ; ) semicolon, which makes it a self-contained statement.
Here’s how you declare a constant:
In the sample code above, you declare a taxRate constant. As you can see, the declaration is very similar to the variable declaration, the only difference being the keyword used: var in the case of a variable and const in the case of a constant.
How to assign values to variables
After you create a variable, you must assign (give) a value to it (or said in Geeeky talk “initialize a variable”) . The ( = ) equal sign is called assignment operator: you assign the value of what is on the right side of the = sign to whatever is on the left side of the = sign. Notice: you cannot perform operations with empty variables.
Ready to fire off your text editor? Let’s get coding!
That’s great! Try experimenting with the code above. For example, change the value of quantity and productPrice, or just come up with your own variables.
How to name variables (and constants)
Choose descriptive names for your variables (var amountDue; rather than var x;): this way your code will be more readable and understandable.
Keep an eye on the following simple rules when you name variables:
1) The first character must be a letter, an ( _ ) underscore, or a ( $ ) dollar sign
5total is wrong: var name cannot start with a number
2) Each character after the first character can be a letter, an ( _ ) underscore, a ( $ ) dollar sign, or a number
3) Spaces and special characters other than ( _ ) and $ are not allowed anywhere
- to tal is wrong: spaces are not allowed;
- total# is wrong: # character is not allowed;
- total£ is wrong: £ character is not allowed.
Take a break and get ready for lesson 5.