Update article.md
This commit is contained in:
parent
721081b25c
commit
6244060545
1 changed files with 47 additions and 48 deletions
|
@ -1,16 +1,16 @@
|
||||||
# Variables
|
# Variables
|
||||||
|
|
||||||
Most of the time, a JavaScript application needs to work with information. Here are 2 examples:
|
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.
|
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.
|
2. A chat application -- the information might include users, messages, and much more.
|
||||||
|
|
||||||
Variables are used to store this information.
|
Variables are used to store this information.
|
||||||
|
|
||||||
## A variable
|
## A variable
|
||||||
|
|
||||||
A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "named storage" for data. We can use variables to store goodies, visitors and other data.
|
A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "named storage" for data. We can use variables to store goodies, visitors, and other data.
|
||||||
|
|
||||||
To create a variable in JavaScript, we need to use the `let` keyword.
|
To create a variable in JavaScript, use the `let` keyword.
|
||||||
|
|
||||||
The statement below creates (in other words: *declares* or *defines*) a variable with the name "message":
|
The statement below creates (in other words: *declares* or *defines*) a variable with the name "message":
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ The statement below creates (in other words: *declares* or *defines*) a variable
|
||||||
let message;
|
let message;
|
||||||
```
|
```
|
||||||
|
|
||||||
Now we can put some data into it by using the assignment operator `=`:
|
Now, we can put some data into it by using the assignment operator `=`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
let message;
|
let message;
|
||||||
|
@ -39,7 +39,7 @@ alert(message); // shows the variable content
|
||||||
*/!*
|
*/!*
|
||||||
```
|
```
|
||||||
|
|
||||||
To be concise we can merge the variable declaration and assignment into a single line:
|
To be concise, we can combine the variable declaration and assignment into a single line:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
let message = 'Hello!'; // define the variable and assign the value
|
let message = 'Hello!'; // define the variable and assign the value
|
||||||
|
@ -53,7 +53,7 @@ We can also declare multiple variables in one line:
|
||||||
let user = 'John', age = 25, message = 'Hello';
|
let user = 'John', age = 25, message = 'Hello';
|
||||||
```
|
```
|
||||||
|
|
||||||
That might seem shorter, but it's not recommended. For the sake of better readability, please use a single line per variable.
|
That might seem shorter, but we don't recommended 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:
|
The multiline variant is a bit longer, but easier to read:
|
||||||
|
|
||||||
|
@ -63,7 +63,7 @@ let age = 25;
|
||||||
let message = 'Hello';
|
let message = 'Hello';
|
||||||
```
|
```
|
||||||
|
|
||||||
Some people also write many variables like that:
|
Some people also define multiple variables in this multiline style:
|
||||||
```js no-beautify
|
```js no-beautify
|
||||||
let user = 'John',
|
let user = 'John',
|
||||||
age = 25,
|
age = 25,
|
||||||
|
@ -78,19 +78,19 @@ let user = 'John'
|
||||||
, message = 'Hello';
|
, message = 'Hello';
|
||||||
```
|
```
|
||||||
|
|
||||||
Technically, all these variants do the same. So, it's a matter of personal taste and aesthetics.
|
Technically, all these variants do the same thing. So, it's a matter of personal taste and aesthetics.
|
||||||
|
|
||||||
|
|
||||||
````smart header="`var` instead of `let`"
|
````smart header="`var` instead of `let`"
|
||||||
In older scripts you may also find another keyword: `var` instead of `let`:
|
In older scripts, you may also find another keyword: `var` instead of `let`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
*!*var*/!* message = 'Hello';
|
*!*var*/!* message = 'Hello';
|
||||||
```
|
```
|
||||||
|
|
||||||
The `var` keyword is *almost* the same as `let`. It also declares a variable, but in a slightly different, "old-school" fashion.
|
The `var` keyword is *almost* the same as `let`. It also declares a variable, but in a slightly different, "old-school" way.
|
||||||
|
|
||||||
There are subtle differences between `let` and `var`, but they do not matter for us yet. We'll cover them in detail later, in the chapter <info:var>.
|
There are subtle differences between `let` and `var`, but they do not matter for us yet. We'll cover them in detail in the chapter <info:var>.
|
||||||
````
|
````
|
||||||
|
|
||||||
## A real-life analogy
|
## A real-life analogy
|
||||||
|
@ -101,10 +101,9 @@ For instance, the variable `message` can be imagined as a box labeled `"message"
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
We can put any value into the box.
|
We can put any value in the box.
|
||||||
|
|
||||||
Also we can change it. The value can be changed as many times as needed:
|
|
||||||
|
|
||||||
|
We can also change it as many times as we want:
|
||||||
```js run
|
```js run
|
||||||
let message;
|
let message;
|
||||||
|
|
||||||
|
@ -137,28 +136,28 @@ alert(message); // Hello world!
|
||||||
```
|
```
|
||||||
|
|
||||||
```smart header="Functional languages"
|
```smart header="Functional languages"
|
||||||
It may be interesting to know that there also exist [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages that forbid changing a variable value. For example, [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/).
|
It's interesting to note that [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages, like [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/), forbid changing variable values.
|
||||||
|
|
||||||
In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can't reuse the old one.
|
In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can't reuse the old one.
|
||||||
|
|
||||||
Though it may seem a little bit odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if not planning to use it soon) is recommended to broaden the mind.
|
Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if you're not planning to use it soon) is recommended to broaden the mind.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Variable naming [#variable-naming]
|
## Variable naming [#variable-naming]
|
||||||
|
|
||||||
There are two limitations for a variable name in JavaScript:
|
There are two limitations on variable names in JavaScript:
|
||||||
|
|
||||||
1. The name must contain only letters, digits, symbols `$` and `_`.
|
1. The name must contain only letters, digits, or the symbols `$` and `_`.
|
||||||
2. The first character must not be a digit.
|
2. The first character must not be a digit.
|
||||||
|
|
||||||
Valid names, for instance:
|
Examples of valid names:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
let userName;
|
let userName;
|
||||||
let test123;
|
let test123;
|
||||||
```
|
```
|
||||||
|
|
||||||
When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word starts with a capital letter: `myVeryLongName`.
|
When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word 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.
|
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.
|
||||||
|
|
||||||
|
@ -176,11 +175,11 @@ Examples of incorrect variable names:
|
||||||
```js no-beautify
|
```js no-beautify
|
||||||
let 1a; // cannot start with a digit
|
let 1a; // cannot start with a digit
|
||||||
|
|
||||||
let my-name; // a hyphen '-' is not allowed in the name
|
let my-name; // hyphens '-' aren't allowed in the name
|
||||||
```
|
```
|
||||||
|
|
||||||
```smart header="Case matters"
|
```smart header="Case matters"
|
||||||
Variables named `apple` and `AppLE` -- are two different variables.
|
Variables named `apple` and `AppLE` are two different variables.
|
||||||
```
|
```
|
||||||
|
|
||||||
````smart header="Non-English letters are allowed, but not recommended"
|
````smart header="Non-English letters are allowed, but not recommended"
|
||||||
|
@ -195,9 +194,9 @@ Technically, there is no error here, such names are allowed, but there is an int
|
||||||
````
|
````
|
||||||
|
|
||||||
````warn header="Reserved names"
|
````warn header="Reserved names"
|
||||||
There is a [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), which cannot be used as variable names, because they are used by the language itself.
|
There is a [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), which cannot be used as variable names because they are used by the language itself.
|
||||||
|
|
||||||
For example, words `let`, `class`, `return`, `function` are reserved.
|
For example: `let`, `class`, `return`, and `function` are reserved.
|
||||||
|
|
||||||
The code below gives a syntax error:
|
The code below gives a syntax error:
|
||||||
|
|
||||||
|
@ -209,17 +208,17 @@ let return = 5; // also can't name it "return", error!
|
||||||
|
|
||||||
````warn header="An assignment without `use strict`"
|
````warn header="An assignment without `use strict`"
|
||||||
|
|
||||||
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value, without `let`. This still works now if we don't put `use strict`. The behavior is kept for compatibility with old scripts.
|
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using `let`. This still works now if we don't put `use strict` in our scripts to maintain compatibility with old scripts.
|
||||||
|
|
||||||
```js run no-strict
|
```js run no-strict
|
||||||
// note: no "use strict" in this example
|
// note: no "use strict" in this example
|
||||||
|
|
||||||
num = 5; // the variable "num" is created if didn't exist
|
num = 5; // the variable "num" is created if it didn't exist
|
||||||
|
|
||||||
alert(num); // 5
|
alert(num); // 5
|
||||||
```
|
```
|
||||||
|
|
||||||
That's a bad practice, it would give an error in the strict mode:
|
This is a bad practice and would cause an error in strict mode:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
"use strict";
|
"use strict";
|
||||||
|
@ -232,13 +231,13 @@ num = 5; // error: num is not defined
|
||||||
|
|
||||||
## Constants
|
## Constants
|
||||||
|
|
||||||
To declare a constant (unchanging) variable, one can use `const` instead of `let`:
|
To declare a constant (unchanging) variable, use `const` instead of `let`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const myBirthday = '18.04.1982';
|
const myBirthday = '18.04.1982';
|
||||||
```
|
```
|
||||||
|
|
||||||
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do it would cause an error:
|
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do so would cause an error:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
const myBirthday = '18.04.1982';
|
const myBirthday = '18.04.1982';
|
||||||
|
@ -246,7 +245,7 @@ const myBirthday = '18.04.1982';
|
||||||
myBirthday = '01.01.2001'; // error, can't reassign the constant!
|
myBirthday = '01.01.2001'; // error, can't reassign the constant!
|
||||||
```
|
```
|
||||||
|
|
||||||
When a programmer is sure that the variable should never change, they can use `const` to guarantee it, and also to clearly show that fact to everyone.
|
When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and clearly communicate that fact to everyone.
|
||||||
|
|
||||||
|
|
||||||
### Uppercase constants
|
### Uppercase constants
|
||||||
|
@ -271,19 +270,19 @@ alert(color); // #FF7F00
|
||||||
Benefits:
|
Benefits:
|
||||||
|
|
||||||
- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
|
- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
|
||||||
- It is much easier to mistype in `"#FF7F00"` than in `COLOR_ORANGE`.
|
- It is much easier to mistype `"#FF7F00"` than `COLOR_ORANGE`.
|
||||||
- When reading the code, `COLOR_ORANGE` is much more meaningful than `#FF7F00`.
|
- 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 them normally? Let's make that clear.
|
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 the value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red), and there are those that are *calculated* in run-time, during the execution, but do not change after the assignment.
|
Being a "constant" just means that a variable's value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are *calculated* in run-time, during the execution, but do not change after their initial assignment.
|
||||||
|
|
||||||
For instance:
|
For instance:
|
||||||
```js
|
```js
|
||||||
const pageLoadTime = /* time taken by a webpage to load */;
|
const pageLoadTime = /* time taken by a webpage to load */;
|
||||||
```
|
```
|
||||||
|
|
||||||
The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant, because it doesn't change after assignment.
|
The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant because it doesn't change after assignment.
|
||||||
|
|
||||||
In other words, capital-named constants are only used as aliases for "hard-coded" values.
|
In other words, capital-named constants are only used as aliases for "hard-coded" values.
|
||||||
|
|
||||||
|
@ -291,41 +290,41 @@ In other words, capital-named constants are only used as aliases for "hard-coded
|
||||||
|
|
||||||
Talking about variables, there's one more extremely important thing.
|
Talking about variables, there's one more extremely important thing.
|
||||||
|
|
||||||
Please name the variables sensibly. Take time to think if needed.
|
Please name your variables sensibly. Take time to think about this.
|
||||||
|
|
||||||
Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code is written by a beginner and which by an experienced developer.
|
Variable naming is one of the most important and complex skills in programming. A quick 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 on modifying and extending the existing code base, rather than writing something completely separate from scratch. And when we return to the code after some time of doing something else, it's much easier to find information that is well-labeled. Or, in other words, when the variables have good names.
|
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-labeled. Or, in other words, when the variables have good names.
|
||||||
|
|
||||||
Please spend some time thinking about the right name for a variable before declaring it. This will repay you a lot.
|
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:
|
Some good-to-follow rules are:
|
||||||
|
|
||||||
- Use human-readable names like `userName` or `shoppingCart`.
|
- Use human-readable names like `userName` or `shoppingCart`.
|
||||||
- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really know what you're doing.
|
- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really know what you're doing.
|
||||||
- Make the name maximally descriptive and concise. Examples of bad names are `data` and `value`. Such a name says nothing. It is only ok to use them if it's exceptionally obvious from the context which data or value is meant.
|
- Make names maximally descriptive and concise. Examples of bad names are `data` and `value`. Such names say nothing. It'ss 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 own mind. If a site visitor is called a "user" then we should name related variables like `currentUser` or `newUser`, but not `currentVisitor` or a `newManInTown`.
|
- Agree on terms within your team and in your own 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 good descriptive-and-concise names in practice is not. Go for it.
|
Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
|
||||||
|
|
||||||
```smart header="Reuse or create?"
|
```smart header="Reuse or create?"
|
||||||
And the last note. There are some lazy programmers who, instead of declaring a new variable, tend to reuse the existing ones.
|
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
|
||||||
|
|
||||||
As a result, the variable is like a box where people throw different things without changing the sticker. What is inside it now? Who knows... We need to come closer and check.
|
As a result, their variables are like boxes into which people throw different things without changing their stickers. What's inside the box now? Who knows? We need to come closer and check.
|
||||||
|
|
||||||
Such a programmer saves a little bit on variable declaration, but loses ten times more on debugging the code.
|
Such programmers save a little bit on variable declaration but lose ten times more on debugging.
|
||||||
|
|
||||||
An extra variable is good, not evil.
|
An extra variable is good, not evil.
|
||||||
|
|
||||||
Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues. Using different variables for different values can even help the engine to optimize.
|
Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues. Using different variables for different values can even help the engine optimize your code.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
We can declare variables to store data. That can be done using `var` or `let` or `const`.
|
We can declare variables to store data by using the `var`, `let`, or `const` keywords.
|
||||||
|
|
||||||
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
|
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
|
||||||
- `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.
|
- `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.
|
- `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.
|
Variables should be named in a way that allows us to easily understand what's inside them.
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue