taskui
This commit is contained in:
parent
db4a880974
commit
06cdd5b84a
23 changed files with 110 additions and 775 deletions
|
@ -7,7 +7,7 @@ For example, this HTML-page shows the "Hello" message:
|
|||
```html run
|
||||
<!doctype html>
|
||||
<script>
|
||||
alert("Hello!");
|
||||
alert("Hello, world!");
|
||||
</script>
|
||||
```
|
||||
|
||||
|
@ -19,15 +19,16 @@ We can also run scripts using [Node.js](https://nodejs.org), it's commonly used
|
|||
|
||||
Depending on the environment, JavaScript may provide platform-specific functionality.
|
||||
|
||||
- In a web browser, JavaScript can manipulate the web-page, send network requests, show messages and so on.
|
||||
- Node.js allows to run a web-server.
|
||||
- In a web browser, JavaScript can manipulate the web-page, send network requests, show messages and so on.
|
||||
- In node.js we can use JavaScript to run a web-server, read and write arbitrary files.
|
||||
- ...And so on.
|
||||
|
||||
...And so on. Even a coffee machine may include its own JavaScript engine, that could allow us to program its recipes.
|
||||
Technically, even a coffee machine can include its own JavaScript engine, to allow programming of coffee recipes.
|
||||
|
||||

|
||||
|
||||
In this tutorial we concentrate on the "core JavaScript", that's the same everywhere.**
|
||||
**In this tutorial we concentrate on the "core JavaScript", that's the same everywhere.**
|
||||
|
||||
After you learn it, you can go in any direction: learn browser functionality, how to write servers and so on.
|
||||
We'll try to keep browser-specific notes at minimum. After you learn the core, you can go in any direction: browsers, frameworks, servers and so on.
|
||||
|
||||
Please turn the page to start learning JavaScript!
|
||||
Turn the page to start learning JavaScript!
|
||||
|
|
|
@ -1,251 +1,14 @@
|
|||
|
||||
# Basic concepts
|
||||
# Code structure
|
||||
|
||||
Let's take a piece of JavaScript code and discuss it line by line.
|
||||
|
||||
Please don't hesitate to open "read more" sections below. They aren't strictly required, but contain valueable information.
|
||||
|
||||
```js run
|
||||
"use strict";
|
||||
|
||||
let message = "Hello!";
|
||||
|
||||
alert(message);
|
||||
```
|
||||
|
||||
Click the "run" icon ▷ in the right-upper corner to see how it works.
|
||||
|
||||
Now we'll go over it line by line.
|
||||
|
||||
## Strict mode
|
||||
|
||||
The first line:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
```
|
||||
|
||||
The code starts with the special directive: `"use strict"`.
|
||||
|
||||
To understand what it means, let's make a short dive into the history of JavaScript.
|
||||
|
||||
JavaScript appeared many years ago, in 1995. For a long time, it evolved without compatibility issues. New features were added to the language while old functionality didn't change.
|
||||
|
||||
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever.
|
||||
|
||||
This was the case until 2009, when the 5th version of the standard appeared. It added new features to the language and modified some of the existing ones.
|
||||
|
||||
Now the important part.
|
||||
|
||||
**To keep the old code working, these modernizations are off by default.** We need to explicitly enable them with a special directive: `"use strict"`
|
||||
|
||||
With that directive on top the script runs in so-called "strict mode". Or, we'd better say "modern mode", because that's what it essentially is.
|
||||
|
||||

|
||||
|
||||
Some JavaScript features enable strict mode automatically, e.g. classes and modules, so that we don't need to write `"use strict"` for them. We'll cover these features later.
|
||||
|
||||
**Here, in the tutorial, we'll always use strict mode, unless explicitly stated otherwise.**
|
||||
|
||||
We're studying modern JavaScript after all. But you'll also see notes about how things work without `use strict`, just in case you come across an old script.
|
||||
|
||||
## Variables
|
||||
|
||||
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 so on.
|
||||
|
||||
The second line declares (creates) a variable with the name `message` and stores the string `"John"` in it:
|
||||
|
||||
```js
|
||||
let message = "Hello!";
|
||||
```
|
||||
|
||||
We could also split this line into two:
|
||||
|
||||
```js
|
||||
let message;
|
||||
message = "Hello!";
|
||||
```
|
||||
|
||||
Here, we first declare the variable with `let message`, and then assign the value.
|
||||
|
||||
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 labeled `"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:
|
||||
```js
|
||||
let message;
|
||||
|
||||
message = "Hello!";
|
||||
|
||||
message = "World!"; // value changed
|
||||
```
|
||||
|
||||
When the value is changed, the old data is removed from the variable:
|
||||
|
||||

|
||||
|
||||
We can also declare multiple variables and copy data from one into another.
|
||||
|
||||
```js run
|
||||
let hello = "Hello!";
|
||||
|
||||
let message;
|
||||
|
||||
*!*
|
||||
// copy the value "Hello!" from hello into message
|
||||
message = hello;
|
||||
*/!*
|
||||
```
|
||||
|
||||
Now we have two variables, both store the same string:
|
||||
|
||||

|
||||
|
||||
````warn header="Re-declaration triggers an error"
|
||||
A variable can be declared only once.
|
||||
|
||||
A repeated declaration of the same variable is an error:
|
||||
|
||||
```js run
|
||||
let message = "One";
|
||||
|
||||
// repeated 'let' leads to an error
|
||||
let message = "Two"; // SyntaxError: 'message' has already been declared
|
||||
```
|
||||
So, we should declare a variable once and then refer to it without `let`.
|
||||
````
|
||||
|
||||
````warn header="Omitting `let` is possible without `use strict`"
|
||||
In the old times, it was possible to create a variable by a mere assignment of the value without using `let`. This still works now if the script runs in the "compatibility mode", without `use strict`:
|
||||
|
||||
```js run no-strict
|
||||
// note: no "use strict" in this example
|
||||
|
||||
num = 5; // the variable "num" is created if it didn't exist
|
||||
|
||||
alert(num); // 5
|
||||
```
|
||||
|
||||
This is a bad practice and would cause an error in strict mode.
|
||||
````
|
||||
|
||||
### 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:
|
||||
|
||||
```js
|
||||
let userName;
|
||||
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 after the first one starts with a capital letter: `myVeryLongName`.
|
||||
|
||||
Examples of incorrect variable names:
|
||||
|
||||
```js no-beautify
|
||||
let 1a; // cannot start with a digit
|
||||
|
||||
let my-name; // hyphens '-' aren't allowed in the name
|
||||
```
|
||||
|
||||
```smart header="Case matters"
|
||||
Variables named `apple` and `AppLE` are two different variables.
|
||||
```
|
||||
|
||||
````smart header="Non-Latin letters are allowed, but not recommended"
|
||||
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
|
||||
|
||||
```js
|
||||
let имя = "...";
|
||||
let 我 = "...";
|
||||
```
|
||||
|
||||
Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if you're writing a small script, it may have a long life ahead. People from other countries may need to read it in the future.
|
||||
````
|
||||
|
||||
````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.
|
||||
|
||||
For example: `let`, `class`, `return`, and `function` are reserved.
|
||||
|
||||
The code below gives a syntax error:
|
||||
|
||||
```js run no-beautify
|
||||
let let = 5; // can't name a variable "let", error!
|
||||
let return = 5; // also can't name it "return", error!
|
||||
```
|
||||
````
|
||||
|
||||
### Other ways to declare a variable
|
||||
|
||||
Besides `let`, there are two other keywords that declare a variable:
|
||||
|
||||
- `var` (e.g. `var message`) -- the outdated way to declare a variable, you can meet it in really old scripts.
|
||||
Please don't use it.
|
||||
- `const` (e.g. `const message`) -- declares a *constant* variable.
|
||||
|
||||
A constant variable must be declared with the initial value, and afterwards it can't be reassigned.
|
||||
|
||||
For example:
|
||||
```js run
|
||||
const birthday = "18.04.1982";
|
||||
|
||||
birthday = "01.01.1970"; // Error: Assignment to constant variable.
|
||||
```
|
||||
|
||||
A person might change their name, but not the birthday. The idea of `const` is to let everyone (including the JavaScript engine)¸know about it.
|
||||
|
||||
## Statements and semicolons
|
||||
|
||||
The third line of our code is:
|
||||
|
||||
```js
|
||||
alert(message);
|
||||
```
|
||||
|
||||
|
||||
<hr>
|
||||
|
||||
|
||||
|
||||
It means that the script should run in the "strict mode".
|
||||
|
||||
Historically,
|
||||
|
||||
If we omit it, then some language features will work a little bit differently. We'll mention the differences later as
|
||||
|
||||
|
||||
or, in other words, in the modern mode of execution.
|
||||
|
||||
There are basically two modes of script execution of a script:
|
||||
- The "strict mode", .
|
||||
- The "strict mode".
|
||||
|
||||
What does it mean?
|
||||
|
||||
Well,
|
||||
|
||||
|
||||
There was a time long ago when JavaScript was a bit different language.
|
||||
|
||||
The core elements of scripts are statements.
|
||||
## Statements
|
||||
|
||||
Statements are syntax constructs and commands that perform actions, make JavaScript "do" something.
|
||||
|
||||
Here's an example of a statement:
|
||||
|
||||
```js run
|
||||
alert('Hello, world!');
|
||||
alert("Hello, world!");
|
||||
```
|
||||
|
||||
Click the "run" icon ▷ in the right-upper corner to see how it works.
|
||||
|
@ -257,32 +20,30 @@ Statements can be separated with a semicolon.
|
|||
For example, here we split "Hello World" into two alerts:
|
||||
|
||||
```js run no-beautify
|
||||
alert('Hello'); alert('World');
|
||||
alert("Hello"); alert("World");
|
||||
```
|
||||
|
||||
Usually, statements are written on separate lines to make the code more readable:
|
||||
|
||||
```js run no-beautify
|
||||
alert('Hello');
|
||||
alert('World');
|
||||
alert("Hello");
|
||||
alert("World");
|
||||
```
|
||||
|
||||
## Semicolons..or not?
|
||||
|
||||
A semicolon may be omitted in most cases when a line break exists.
|
||||
|
||||
This would also work:
|
||||
|
||||
```js run no-beautify
|
||||
alert('Hello')
|
||||
alert('World')
|
||||
alert("Hello")
|
||||
alert("World")
|
||||
```
|
||||
|
||||
Here, JavaScript interprets the line break as an "implicit" semicolon. This is called an [automatic semicolon insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion).
|
||||
Usually, JavaScript interprets the line break as an "implicit" semicolon. This is called an [automatic semicolon insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion).
|
||||
|
||||
**In most cases, a newline implies a semicolon. But "in most cases" does not mean "always"!**
|
||||
|
||||
There are cases when a newline does not mean a semicolon.
|
||||
|
||||
For example:
|
||||
But there are exceptions, like this:
|
||||
|
||||
```js run no-beautify
|
||||
alert(1 +
|
||||
|
@ -291,11 +52,9 @@ alert(1 +
|
|||
|
||||
The code outputs `3` because JavaScript does not insert semicolons after the plus `+`. It is intuitively obvious that if the line ends with a plus `"+"`, then it is an incomplete expression, that's continued on the next line. And in this case that works as intended.
|
||||
|
||||
**But there are situations where JavaScript "fails" to assume a semicolon where it is really needed.**
|
||||
**But there are situations where our intuition differs from JavaScript auto-insertion rules.**
|
||||
|
||||
**TODO: The section below is optional, so it's collapsed by default - make it a hint on first open?**
|
||||
|
||||
**TODO: design this.**
|
||||
That may lead to subtle errors.
|
||||
|
||||
````spoiler header="Read more about it"
|
||||
|
||||
|
@ -305,14 +64,14 @@ If you're curious to see a concrete example of such an error, check this code ou
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
If the code is too complex to understand, that's all right. You don't have to.
|
||||
The code may be too advanced to understand right now, but that's all right.
|
||||
|
||||
All you need now is to run the code and remember the result: it shows `1` then `2`.
|
||||
All you need to do is to run the code and remember the result: it shows `1` then `2`.
|
||||
|
||||
Let's add an `alert` before the code and *not* finish it with a semicolon:
|
||||
|
||||
```js run no-beautify
|
||||
alert("Without a semicolon after me - error")
|
||||
alert("Without a semicolon after the alert - error")
|
||||
|
||||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
@ -326,7 +85,7 @@ alert("With a semicolon after me - all ok");
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
The error in the no-semicolon variant occurs because JavaScript doesn't "auto-insert" a semicolon on a newline before square brackets `[...]`.
|
||||
The error in the no-semicolon variant occurs because JavaScript doesn't "auto-insert" a semicolon if a newline is followed by squares brackets `[...]`.
|
||||
|
||||
So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. Here's how the engine sees it:
|
||||
|
||||
|
@ -337,9 +96,9 @@ alert("There will be an error")[1, 2].forEach(alert)
|
|||
But such a merge in this case is just wrong, hence the error. This can happen in other situations as well.
|
||||
````
|
||||
|
||||
To prevent such errors, we recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community.
|
||||
|
||||
We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer --
|
||||
especially for a beginner -- to use them.
|
||||
Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them.
|
||||
|
||||
## Comments
|
||||
|
||||
|
@ -354,9 +113,9 @@ The rest of the line is a comment. It may occupy a full line of its own or follo
|
|||
Like here:
|
||||
```js run
|
||||
// This comment occupies a line of its own
|
||||
alert('Hello');
|
||||
alert("Hello");
|
||||
|
||||
alert('World'); // This comment follows the statement
|
||||
alert("World"); // This comment follows the statement
|
||||
```
|
||||
|
||||
**Multiline comments start with a forward slash and an asterisk <code>/*</code> and end with an asterisk and a forward slash <code>*/</code>.**
|
||||
|
@ -367,8 +126,8 @@ Like this:
|
|||
/* An example with two messages.
|
||||
This is a multiline comment.
|
||||
*/
|
||||
alert('Hello');
|
||||
alert('World');
|
||||
alert("Hello");
|
||||
alert("World");
|
||||
```
|
||||
|
||||
The content of comments is ignored, so if we put code inside <code>/* ... */</code>, it won't execute.
|
||||
|
@ -377,9 +136,9 @@ Sometimes it can be handy to temporarily disable a part of code:
|
|||
|
||||
```js run
|
||||
/* Commenting out the code
|
||||
alert('Hello');
|
||||
alert("Hello");
|
||||
*/
|
||||
alert('World');
|
||||
alert("World");
|
||||
```
|
||||
|
||||
```smart header="Use hotkeys!"
|
||||
|
@ -395,7 +154,7 @@ Such code will die with an error:
|
|||
/*
|
||||
/* nested comment ?!? */
|
||||
*/
|
||||
alert( 'World' );
|
||||
alert( "World" );
|
||||
```
|
||||
````
|
||||
|
||||
|
@ -403,4 +162,26 @@ Please, don't hesitate to comment your code.
|
|||
|
||||
Comments increase the overall code footprint, but that's not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don't appear in the working scripts. Therefore, comments do not have negative effects on production at all.
|
||||
|
||||
Later in the tutorial there will be a chapter <info:code-quality> that also explains how to write better comments.
|
||||
## Strict mode
|
||||
|
||||
JavaScript appeared many years ago, in 1995. Then ,for a long time, it evolved without compatibility issues. New features were added to the language while old functionality didn't change.
|
||||
|
||||
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever.
|
||||
|
||||
This was the case until 2009, when the 5th version of the standard appeared. It added new features to the language and modified some of the existing ones.
|
||||
|
||||
Now the important part.
|
||||
|
||||
**To keep the old code working, these newer modifications are off by default.**
|
||||
|
||||
We need to explicitly enable them with a special directive: `"use strict"`
|
||||
|
||||
With that directive on top the script runs in so-called "strict mode". Or, we'd better say "modern mode", because that's what it essentially is.
|
||||
|
||||

|
||||
|
||||
Some JavaScript features enable strict mode automatically, e.g. classes and modules, so that we don't need to write `"use strict"` for them. We'll cover these features later.
|
||||
|
||||
**Here, in the tutorial, we'll always use strict mode, unless explicitly stated otherwise.**
|
||||
|
||||
We're studying modern JavaScript after all. But you'll also see notes about how things work without `use strict`, just in case you come across an old script.
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
In the code below, each line corresponds to the item in the task list.
|
||||
|
||||
```js run
|
||||
let admin, name; // can declare two variables at once
|
||||
|
||||
name = "John";
|
||||
|
||||
admin = name;
|
||||
|
||||
alert( admin ); // "John"
|
||||
```
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
importance: 2
|
||||
|
||||
---
|
||||
|
||||
# Working with variables
|
||||
|
||||
1. Declare two variables: `admin` and `name`.
|
||||
2. Assign the value `"John"` to `name`.
|
||||
3. Copy the value from `name` to `admin`.
|
||||
4. Show the value of `admin` using `alert` (must output "John").
|
|
@ -0,0 +1,21 @@
|
|||
## The variable for our planet
|
||||
|
||||
That's simple:
|
||||
|
||||
```js
|
||||
let ourPlanetName = "Earth";
|
||||
```
|
||||
|
||||
Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
|
||||
|
||||
## The name of the current visitor
|
||||
|
||||
```js
|
||||
let currentUserName = "John";
|
||||
```
|
||||
|
||||
Again, we could shorten that to `userName` if we know for sure that the user is current.
|
||||
|
||||
Modern editors and autocomplete make long variable names easy to write. Don't save on them. A name with 3 words in it is fine.
|
||||
|
||||
And if your editor does not have proper autocompletion, get [a new one](/code-editors).
|
|
@ -0,0 +1,8 @@
|
|||
importance: 3
|
||||
|
||||
---
|
||||
|
||||
# Giving the right name
|
||||
|
||||
1. Create a variable with the name of our planet. How would you name such a variable?
|
||||
2. Create a variable to store the name of a current visitor to a website. How would you name that variable?
|
|
@ -0,0 +1,5 @@
|
|||
We generally use upper case for constants that are "hard-coded". Or, in other words, when the value is known prior to execution and directly written into the code.
|
||||
|
||||
In this code, `birthday` is exactly like that. So we could use the upper case for it.
|
||||
|
||||
In contrast, `age` is evaluated in run-time. Today we have one age, a year after we'll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit "less of a constant" than `birthday`: it is calculated, so we should keep the lower case for it.
|
|
@ -0,0 +1,24 @@
|
|||
importance: 4
|
||||
|
||||
---
|
||||
|
||||
# Uppercase const?
|
||||
|
||||
Examine the following code:
|
||||
|
||||
```js
|
||||
const birthday = '18.04.1982';
|
||||
|
||||
const age = someCode(birthday);
|
||||
```
|
||||
|
||||
Here we have a constant `birthday` date and the `age` is calculated from `birthday` with the help of some code (it is not provided for shortness, and because details don't matter here).
|
||||
|
||||
Would it be right to use upper case for `birthday`? For `age`? Or even for both?
|
||||
|
||||
```js
|
||||
const BIRTHDAY = '18.04.1982'; // make uppercase?
|
||||
|
||||
const AGE = someCode(BIRTHDAY); // make uppercase?
|
||||
```
|
||||
|
342
1-js/01-getting-started/03-variables/article.md
Normal file
342
1-js/01-getting-started/03-variables/article.md
Normal file
|
@ -0,0 +1,342 @@
|
|||
# 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](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, use the `let` keyword.
|
||||
|
||||
The statement below creates (in other words: *declares*) a variable with the name "message":
|
||||
|
||||
```js
|
||||
let message;
|
||||
```
|
||||
|
||||
Now, we can put some data into it by using the assignment `=`:
|
||||
|
||||
```js
|
||||
let message;
|
||||
|
||||
*!*
|
||||
message = "Hello"; // store the string
|
||||
*/!*
|
||||
```
|
||||
|
||||
The string is now saved into the memory area associated with the variable. We can access it using the variable name:
|
||||
|
||||
```js run
|
||||
let message;
|
||||
message = "Hello!";
|
||||
|
||||
*!*
|
||||
alert(message); // shows the variable content
|
||||
*/!*
|
||||
```
|
||||
|
||||
To be concise, we can combine the variable declaration and assignment into a single line:
|
||||
|
||||
```js run
|
||||
let message = "Hello!"; // define the variable and assign the value
|
||||
|
||||
alert(message); // Hello!
|
||||
```
|
||||
|
||||
We can also declare multiple variables in one line:
|
||||
|
||||
```js no-beautify
|
||||
let user = "John", age = 25, message = "Hello";
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
let user = "John";
|
||||
let age = 25;
|
||||
let message = "Hello";
|
||||
```
|
||||
|
||||
Some people also define multiple variables in this multiline style:
|
||||
```js no-beautify
|
||||
let user = "John",
|
||||
age = 25,
|
||||
message = "Hello";
|
||||
```
|
||||
|
||||
...Or even in the "comma-first" style:
|
||||
|
||||
```js no-beautify
|
||||
let user = "John"
|
||||
, age = 25
|
||||
, message = "Hello";
|
||||
```
|
||||
|
||||
Technically, all these variants do the same thing. So, it's a matter of personal taste and aesthetics.
|
||||
|
||||
````smart header="`var` instead of `let`"
|
||||
In older scripts, you may also find another keyword: `var` instead of `let`:
|
||||
|
||||
```js
|
||||
*!*var*/!* message = "Hello";
|
||||
```
|
||||
|
||||
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 now. We'll cover them in the optional chapter <info:var>. We should never use `var` in modern scripts.
|
||||
````
|
||||
|
||||
## 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 labeled `"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:
|
||||
```js run
|
||||
let message;
|
||||
|
||||
message = "Hello!";
|
||||
|
||||
message = "World!"; // value changed
|
||||
|
||||
alert(message);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```js run
|
||||
let hello = "Hello!";
|
||||
|
||||
let message;
|
||||
|
||||
*!*
|
||||
// copy "Hello!" from hello into message
|
||||
message = hello;
|
||||
*/!*
|
||||
|
||||
// now two variables hold the same data
|
||||
alert(hello); // Hello world!
|
||||
alert(message); // Hello world!
|
||||
```
|
||||
|
||||
Now we have two variables, both store the same string:
|
||||
|
||||

|
||||
|
||||
|
||||
````warn header="Re-declaration triggers an error"
|
||||
A variable can be declared only once.
|
||||
|
||||
A repeated declaration of the same variable is an error:
|
||||
|
||||
```js run
|
||||
let message = "One";
|
||||
|
||||
// repeated 'let' leads to an error
|
||||
let message = "Two"; // SyntaxError: 'message' has already been declared
|
||||
```
|
||||
So, we should declare a variable once and then refer to it without `let`.
|
||||
````
|
||||
|
||||
````warn header="Without `use strict` it's possible to assign to an undeclared variable"
|
||||
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, without strict mode:
|
||||
|
||||
```js run no-strict
|
||||
// note: no "use strict" in this example
|
||||
|
||||
num = 5; // the variable "num" is created if it didn't exist
|
||||
|
||||
alert(num); // 5
|
||||
```
|
||||
|
||||
This is a bad practice and would cause an error in strict mode:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
*!*
|
||||
num = 5; // error: num is not defined
|
||||
*/!*
|
||||
```
|
||||
````
|
||||
|
||||
|
||||
### 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:
|
||||
|
||||
```js
|
||||
let userName;
|
||||
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 after the first one 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:
|
||||
|
||||
```js run untrusted
|
||||
let $ = 1; // declared a variable with the name "$"
|
||||
let _ = 2; // and now a variable with the name "_"
|
||||
|
||||
alert($ + _); // 3
|
||||
```
|
||||
|
||||
Examples of incorrect variable names:
|
||||
|
||||
```js no-beautify
|
||||
let 1a; // cannot start with a digit
|
||||
|
||||
let my-name; // hyphens '-' aren't allowed in the name
|
||||
```
|
||||
|
||||
```smart header="Case matters"
|
||||
Variables named `apple` and `AppLE` are two different variables.
|
||||
```
|
||||
|
||||
````smart header="Non-Latin letters are allowed, but not recommended"
|
||||
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
|
||||
|
||||
```js
|
||||
let имя = '...';
|
||||
let 我 = '...';
|
||||
```
|
||||
|
||||
Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if you're writing a small script, it may have a long life ahead. People from other countries may need to read it in the future.
|
||||
````
|
||||
|
||||
````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.
|
||||
|
||||
For example: `let`, `class`, `return`, and `function` are reserved.
|
||||
|
||||
The code below gives a syntax error:
|
||||
|
||||
```js run no-beautify
|
||||
let let = 5; // can't name a variable "let", error!
|
||||
let return = 5; // also can't name it "return", error!
|
||||
```
|
||||
````
|
||||
|
||||
## Constants
|
||||
|
||||
To declare a constant (unchanging) variable, use `const` instead of `let`:
|
||||
|
||||
```js
|
||||
const myBirthday = '18.04.1982';
|
||||
```
|
||||
|
||||
Variables declared using `const` are called "constants". They cannot be reassigned. An attempt to do so would cause an error:
|
||||
|
||||
```js run
|
||||
const myBirthday = '18.04.1982';
|
||||
|
||||
myBirthday = '01.01.2001'; // error, can't reassign the constant!
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.
|
||||
|
||||
Such constants are named using capital letters and underscores.
|
||||
|
||||
For instance, let's make constants for colors in so-called "web" (hexadecimal) format:
|
||||
|
||||
```js run
|
||||
const COLOR_RED = "#F00";
|
||||
const COLOR_GREEN = "#0F0";
|
||||
const COLOR_BLUE = "#00F";
|
||||
const COLOR_ORANGE = "#FF7F00";
|
||||
|
||||
// ...when we need to pick a color
|
||||
let color = COLOR_ORANGE;
|
||||
alert(color); // #FF7F00
|
||||
```
|
||||
|
||||
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 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:
|
||||
```js
|
||||
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.
|
||||
|
||||
In other words, capital-named constants are only used as aliases for "hard-coded" values, known prior to execution.
|
||||
|
||||
## 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 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 modifying and extending an existing code base rather than writing something completely new from scratch. When we look at someone else's code, and even if we return to our code after 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 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`, `c`, unless you really 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 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 descriptive and concise variable names in practice is not. Go for it.
|
||||
|
||||
```smart header="Reuse or create?"
|
||||
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
|
||||
|
||||
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 programmers save a little bit on variable declaration but lose ten times more on debugging.
|
||||
|
||||
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 optimize your code.
|
||||
```
|
||||
|
||||
## 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.
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 2.5 KiB |
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
Loading…
Add table
Add a link
Reference in a new issue