Variables
Most of the time, a JavaScript application needs to work with information. Here are two examples: 1. An online shop – the information might include goods being sold and a shopping cart. 2. A chat application – the information might include users, messages, and much more. Variables are used to store this information.
A variable
A variable) is a “named storage” for data. We can use variables to store goodies, visitors, and other data. To create a variable in JavaScript, use the let keyword. The statement below creates (in other words: declares) a variable with the name “message”: Now, we can put some data into it by using the assignment operator =: The string is now saved into the memory area associated with the variable. We can access it using the variable name: To be concise, we can combine the variable declaration and assignment into a single line: We can also declare multiple variables in one line: That might seem shorter, but we don’t recommend it. For the sake of better readability, please use a single line per variable. The multiline variant is a bit longer, but easier to read: Some people also define multiple variables in this multiline style: …Or even in the “comma-first” style: Technically, all these variants do the same thing. So, it’s a matter of personal taste and aesthetics. !var/! message = ‘Hello’;
A real-life analogy
We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it. For instance, the variable message can be imagined as a box labelled “message” with the value “Hello!” in it: We can put any value in the box. We can also change it as many times as we want: When the value is changed, the old data is removed from the variable: We can also declare two variables and copy data from one into the other. let message = “This”; // repeated ‘let’ leads to an error let message = “That”; // SyntaxError: ‘message’ has already been declared
Variable naming [#variable-naming]
There are two limitations on variable names in JavaScript: 1. The name must contain only letters, digits, or the symbols \( and _. 2. The first character must not be a digit. Examples of valid names: When the name contains multiple words, camelCase is commonly used. That is: words go one after another, with each word except the first starting with a capital letter: myVeryLongName. What's interesting -- the dollar sign '\)’ and the underscore ‘_’ can also be used in names. They are regular symbols, just like letters, without any special meaning. These names are valid: Examples of incorrect variable names: let имя = ‘…’; let 我 = ‘…’; let let = 5; // can’t name a variable “let”, error! let return = 5; // also can’t name it “return”, error! // note: no “use strict” in this example num = 5; // the variable “num” is created if it didn’t exist alert(num); // 5 “use strict”; num = 5; // error: num is not defined
Constants
To declare a constant (unchanging) variable, use const instead of let: Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so would cause an error: When a programmer is sure that a variable will never change, they can declare it with const to guarantee and communicate that fact to everyone.
Uppercase constants
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution. Such constants are named using capital letters and underscores. For instance, let’s make constants for colors in so-called “web” (hexadecimal) format: Benefits: - COLOR_ORANGE is much easier to remember than “#FF7F00”. - It is much easier to mistype “#FF7F00” than COLOR_ORANGE. - When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00. When should we use capitals for a constant and when should we name it normally? Let’s make that clear. Being a “constant” just means that a variable’s value never changes. But some constants are known before execution (like a hexadecimal value for red) and some constants are calculated in run-time, during the execution, but do not change after their initial assignment. For instance: The value of pageLoadTime is not known before the page load, so it’s named normally. But it’s still a constant because it doesn’t change after the assignment. In other words, capital-named constants are only used as aliases for “hard-coded” values.
Name things right
Talking about variables, there’s one more extremely important thing. A variable name should have a clean, obvious meaning, describing the data that it stores. Variable naming is one of the most important and complex skills in programming. A glance at variable names can reveal which code was written by a beginner versus an experienced developer. In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it’s much easier to find information that is well-labelled. Or, in other words, when the variables have good names. Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely. Some good-to-follow rules are: - Use human-readable names like userName or shoppingCart. - Stay away from abbreviations or short names like a, b, and c, unless you know what you’re doing. - Make names maximally descriptive and concise. Examples of bad names are data and value. Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing. - Agree on terms within your team and in your mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown. Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
Summary
We can declare variables to store data by using the var, let, or const keywords. - let – is a modern variable declaration. - var – is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover subtle differences from let in the chapter info:var, just in case you need them. - const – is like let, but the value of the variable can’t be changed. Variables should be named in a way that allows us to easily understand what’s inside them.
let message; *!* message = 'Hello'; // store the string 'Hello' in the variable named message */!*
Follow the lesson from Microsoft Web-Dev-For-Beginners course