En muchos casos es necesario desarrollar una aplicación en JavaScript que trabaje y manipule información, como por ejemplo: podemos crear una tienda en línea que pueda incluir información de productos vendidos e incluso un carrito de compras. O también podemos diseñar una app de chat que maneje información tal como usuarios, mensajes, entre otras.
Es aquí donde entran en juego las variables, ya que vamos a usarlas para albergar información o contents en ellas.
What is a variable?
A variable is a special storage space that we can name according to the rules that JS has for this process. In them we can save data such as numbers, text strings, number of visitors, among others. The limits are defined by you.
Para crear una variable es necesario usar la keyword let.
In the following code I show you how to declare a variable called message.
let message;
If we use the assignment operator ( = ), we can assign values to it.
let message; message = 'Hello!'; // Here we are saving this text string in the message variable
The srting or string is now stored in the memory area associated with the message variable. We can access it using the name we assign to the variable:
let message; message = 'Hello!'; alert (message); // With this we make an alert that shows the variable content
To be specific, we can combine the declaration and the variable assignment in one line:
let message = 'Hello!'; // Here we define the variable and assign the value alert (message); // Hi!
We can also declare multiple variables on one line if we separate them by commas. Example:
let Username = 'Juan', edad = 25, mensaje = 'Hello';
The above example may seem shorter, but it is not the most recommended. For better reading, use a single line per declared variable.
The multi-line variant may be a bit longer, but it is easier to read:
let user = 'Juan'; let age = 25; let message = 'Hello';
Some programmers also write many variables like this:
let user = 'John', age = 25, message = 'Hello';
Or they even promote the "comma first" style:
let user = 'John', age = 25, message = 'Hello';
Technically, all of these variants do the same. Therefore, it is a matter of personal taste and aesthetics.
Use the var keyword instead of the let keyword
In scripts anteriores también puedes encontrar otra palabra clave: denominada var instead of the one we use in the examples with let:
var message = 'Hello!';
The key word var is almost the same as the keyword let. It can also be used to declare a variable, but in a slightly different, "old-school" way.
How to name a variable?
You can give almost any name to a variable, however, you must follow two basic guidelines:
- The variable name must contain only letters, numbers, and / or symbols $ and _.
- No variable name must begin with a number.
Here are some valid variable names:
let User_Name; let The_best_01$;
When the name contains multiple words, a practice called camelCase . That is to say: the words go one after another, and each word begins with a capital letter: This would be a very long name.
Another interesting fact is that the dollar sign '$'and the underscore '_' they can also be used in variable names or as variable names. They are regular symbols, just like letters, without any special meaning.
These names are also valid:
let $ = 4; // declare a variable with the name "$" let _ = 5; // and now a variable with the name "_" alert ($ + _); // 9
However, these are variable names totally wrong:
let 26mj; // cannot start with a digit let my-User; // a dash '-' is not allowed in the name
Note: The use of upper and lower case does matter. This means that the variable User is totally different from the variable user.
Reserved names in JS
Surely you ask yourself "What are reserved names?" Well, it is simply a list of reserved words, which cannot be used as variable names, since they are used by the JavaScript language itself.
For example, the words let, class, return, function, among others, are reserved. For the same reason, the following code will give you a syntax error:
let return; // cannot name a variable "return", error! let function; // can't call "function" either, error!
Name the variables well
Speaking of variables, there is one more thing that is extremely important.
Please name the variables sensibly. Take the time to think if necessary.
El nombramiento de variables es una de las habilidades más importantes y complejas de la programming. Un vistazo rápido a los nombres de variables puede revelar qué código está escrito por un principiante y cuál por un desarrollador experimentado.
In a real project, most of the time is spent modifying and extending the existing code base, rather than writing something completely separate from scratch. And when we go back to the code after a while of doing something else, it is much easier to find information that is well labeled. Or, in other words, when variables have good names.
Spend some time thinking about the correct name for a variable before declaring it. This will pay off a lot.
Some good rules to follow are:
- Use human readable names like Username or Buyerof Items.
- Stay away from abbreviations or short names like to, b, or c, unless you really know what you are doing.
- Make the name maximum descriptive and concise. Examples of bad names are data and values. Such names say nothing. It's only okay to use them if it's exceptionally obvious from the context of what data or values you're referring to.
- Agree on the terms within your team and in your own mind. If a visitor to the site is called a "user", we should name related variables like User, new user, but no Visitor or New Individual.
Sounds simple? Indeed it is, but creating good concise and descriptive names in practice is not. Go for it.