Переменные

Одно из самых фундаментальных понятий программирования заключается в том, что программы должны хранить информацию в памяти, чтобы использовать и изменять эту информацию. Практически во всех компьютерных языках для этого используются переменные. Они дают метод маркировки данных описательным термином, который помогает другим читателям и нам в понимании программы. Рассматривайте переменные как информационные контейнеры: их функция — классифицировать и хранить данные в памяти, чтобы ваша программа могла их использовать.

Переменные и имена переменных

Переменная — это просто обозначенный участок памяти, в котором программа может хранить данные. Переменные обычно могут быть изменены. То есть мы можем присвоить переменной новое значение.

let answer = 41;
answer = 42;
console.log(answer)
/*
When JavaScript sees line 1 of this code, it sets aside a bit of memory and stores the value 41 in that area. It also creates a variable named answer that we can use to access that value.
On line 2, we reassign the value 42 to the variable named answer. That is, JavaScript makes answer refer to a new value. In particular, it's important to realize that we're not changing the value of 41 -- we're putting a completely new value in the answer variable.
Finally, on line 3, we log the value of the answer variable to the JavaScript log. To determine what value it needs to log, JavaScript retrieves the value stored in the location used by the variable.
*/

Именование переменных

Имя переменной должно правильно и кратко передавать данные, содержащиеся в переменной. Может быть довольно сложно запомнить, какие типы информации содержит каждая переменная в больших приложениях. Если вы используете имена, которые не являются описательными, например, x, вы можете забыть, какие данные представляет эта переменная.

Объявление и присвоение переменных

Объявление переменной — это оператор, который указывает движку JavaScript выделить память для переменной с определенным именем. Он также может предоставить начальное значение для переменной. Существуют различные способы объявления переменных в JavaScript; однако ключевое слово let является предпочтительным методом в текущем JavaScript:

> let firstName
/* Here, we're telling the interpreter that we want to use a variable named firstName to store some information. If you reference this variable in node, it evaluates as undefined:*/
> firstName
= undefined
/* From this, we can see that firstName was initialized with a value of undefined.*/
/*To assign a more useful value, we can use an initializer in the declaration:*/
> let firstName = 'Mitchell'
> firstName
'Mitchell'
/* As you can see, we've now stored the string 'Mitchell' in memory. We can use firstName as a label for that string elsewhere in the program: */
> console.log(`Your first name is ${firstName}`)
'Your first name is Mitchell'
/* Keep in mind that firstName isn't permanently tied to the same string, 'Mitchell'. In fact, we can reassign it to any other value, not just strings: */
> firstName = 'Joe'
= 'Joe'
> firstName = 42
= 42
// Example
> let a = 4
> let b = a
> a = 7
= 7
> b
=4

Объявление констант

Ключевое слово const похоже на ключевое слово let тем, что оно позволяет вам определять и инициализировать идентификаторы констант:

> const firstName = 'Mitchell'
> firstName
= Mitchell
/* Constants have an immutable relationship with their values. A constant, unlike a variable, cannot be assigned a new value once declared. The constant will remain at that value until it is no longer required. */
const INTEREST_RATE = 0.075;
INTEREST_RATE = 0.080; /* Uncaught TypeError: Assignment to constant variable.*/
/* Using constants is a great way to label a value with a name that makes your code more descriptive and easier to understand. */
/* A standard convention when naming constants is to use all uppercase letters and digits in the name; if the name contains multiple words, use underscores to separate the words. */
//Note that const declarations require a value:
const foo; /* SyntaxError: Missing initializer in const declaration */

Область действия переменной

Область действия переменной указывает, где она доступна в программе. Область действия переменной определяется тем, где она объявлена. Переменные, определенные с помощью ключевых слов let или const в JavaScript, имеют область действия блока. Блок — это связанная группа операторов и выражений JavaScript, заключенная в пару фигурных скобок. Мы будем использовать оператор if для демонстрации, потому что они обычно содержат по крайней мере один блок:

if (expression) {  // block starts at {
  doSomething();   // block body
}                  // block ends here
/* The expression between the parenthesis (()) is evaluated by JavaScript. If it returns true, JavaScript runs the code contained within the block. Otherwise, it proceeds to the code after the block. When the expression is true, we call doSomething(). */
if (1 === 1) {
  let a = 'foo';
}
console.log(a); // ReferenceError: a is not defined
/* In the following example, the condition is always true, thus JavaScript executes the let statement on line 2. This code creates a variable called a and assigns it to the string 'foo.' However, because let generates a block-scoped variable, an is not available outside the block, we receive an error on line 5. */
/* The error tells you that a isn't available on line 5. In other words, it isn't in scope outside of the if block. */
/* If, on the other hand, you declare the variable outside the if block, the variable is available within the block as well as after the block ends. */
let a = 'foo';
if (1 === 1) {
  a = 'bar';
}
console.log(a);    // => 'bar'
/* Because an is available within the block, this code produces the string "bar." As a result, we can reassign it to a different value within the block. In other words, this an is more general than the a variable in the preceding example. */