Depending on the reason for the creation of your script, you will need to work with the information.
If you are making an Internet shop, you will work with the goods and the basket. If you create the chat, you will have visitors, messages and so on.
To store information, the variables are used.
The variable consists of a name and a dedicated memory which corresponds to it. To declare or, in other words, to create a variable, the keyword “var” is used:
After the declaration, you can write the data in the variable:
var message; message = 'Hello'; // save a string in the variable
This data will be stored in the corresponding memory area and available in the future:
var message; message = 'Hello!'; alert (message); // Displays the contents of a variable
You can combine the declaration of the variable and writing the data into it:
var message = 'Hello!'; It is possible to declare several variables at once: var user = 'John', age = 25, message = 'Hello';
- The name can consist of letters, numbers, symbols, and $ _
- The first character must not be a digit.
var myName; var test123; Such symbols as “$” or “_” are considered to be usual, like letters: var $ = 1; var _ = 2; alert( $ + _ ); // 3 And such variables will be incorrect: var 1a; // starts with a number var my-name; //'-' is restricted Constants A constant is a value that never changes. They are usually called capitalized: var COLOR_RED = "#F00"; var COLOR_GREEN = "#0F0"; var COLOR_BLUE = "#00F"; var COLOR_ORANGE = "#FF7F00"; var color = COLOR_ORANGE; alert( color ); // #FF7F00
Technically, the constant is a usual variable and it can be changed. We just agree not to do that.
COLOR_ORANGEis an understandable name. Using
#FF7F00is more complicated.
- It is much more simple to make a typo in such a string as
COLOR_ORANGEit would be easier to notice.
Technically, you can simply write the value of the variable and without declaration, but this is not recommended for several reasons.
Variables which are named CAPITALIZED are constants and never change. Usually, they are used for convenience.