Переменные
В зависимости от того, для чего вы делаете скрипт, понадобится работать с информацией.
Если это электронный магазин – то это товары, корзина. Если чат – посетители, сообщения и так далее.
Чтобы хранить информацию, используются переменные.
Переменная
Переменная состоит из имени и выделенной области памяти, которая ему соответствует.
Для объявления или, другими словами, создания переменной используется ключевое слово var :

После объявления, можно записать в переменную данные:

Эти данные будут сохранены в соответствующей области памяти и в дальнейшем доступны при обращении по имени:

Для краткости можно совместить объявление переменной и запись данных:

Можно даже объявить несколько переменных сразу:

Аналогия из жизни
Проще всего понять переменную, если представить её как «коробку» для данных, с уникальным именем.
Например, переменная message – это коробка, в которой хранится значение "Hello!" :

В коробку можно положить любое значение, а позже – поменять его. Значение в переменной можно изменять сколько угодно раз:

При изменении значения старое содержимое переменной удаляется.

Можно объявить две переменные и копировать данные из одной в другую:

Существуют функциональные языки программирования, в которых значение переменной менять нельзя. Например, Scala или Erlang.
В таких языках положил один раз значение в коробку – и оно хранится там вечно, ни удалить ни изменить. А нужно что-то другое сохранить – изволь создать новую коробку (объявить новую переменную), повторное использование невозможно.
С виду – не очень удобно, но, как ни странно, и на таких языках вполне можно успешно программировать. Более того, оказывается, что в ряде областей, например в распараллеливании вычислений, они имеют преимущества. Изучение какого-нибудь функционального языка рекомендуется для расширения кругозора.
Имена переменных
На имя переменной в JavaScript наложены всего два ограничения.
- Имя может состоять из: букв, цифр, символов $ и _
- Первый символ не должен быть цифрой.

Что особенно интересно – доллар ‘$’ и знак подчеркивания ‘_’ являются такими же обычными символами, как буквы:

А такие переменные были бы неправильными:

Переменные apple и AppLE – две разные переменные.
В названии переменных можно использовать и русские буквы, например:

Технически, ошибки здесь нет, но на практике сложилась традиция использовать в именах только английские буквы.
Существует список зарезервированных слов, которые нельзя использовать для переменных, так как они используются самим языком, например: var, class, return, export и др.
Например, такой пример выдаст синтаксическую ошибку:

Важность директивы var
В старом стандарте JavaScript разрешалось создавать переменную и без var , просто присвоив ей значение:

В режиме "use strict" так делать уже нельзя.
Следующий код выдаст ошибку:

Обратим внимание, директиву use strict нужно ставить до кода, иначе она не сработает:

Если же вы собираетесь поддерживать IE8-, то у меня для вас ещё одна причина всегда использовать var .
Следущий документ в IE8- ничего не выведет, будет ошибка:

Это потому, что переменная test не объявлена через var и совпадает с id элемента <div> . Даже не спрашивайте почему – это ошибка в браузере IE до версии 9.
Самое «забавное» то, что такая ошибка присвоения значений будет только в IE8- и только если на странице присутствует элемент с id , совпадающим с именем переменной.
Такие ошибки особенно «весело» исправлять и отлаживать.
Вывод простой – всегда объявляем переменные через var , и сюрпризов не будет. Даже в старых IE.
Константы
Константа – это переменная, которая никогда не меняется. Как правило, их называют большими буквами, через подчёркивание. Например:

Технически, константа является обычной переменной, то есть её можно изменить. Но мы договариваемся этого не делать.
Зачем нужны константы? Почему бы просто не писать var color = "#FF7F00" ?
- Во-первых, константа COLOR_ORANGE – это понятное имя. По присвоению var color="#FF7F00" непонятно, что цвет – оранжевый. Иными словами, константа COLOR_ORANGE является «понятным псевдонимом» для значения #FF7F00 .
- Во-вторых, опечатка в строке, особенно такой сложной как #FF7F00 , может быть не замечена, а в имени константы её допустить куда сложнее.
Константы используют вместо строк и цифр, чтобы сделать программу понятнее и избежать ошибок.
HTML <var> id Attribute
An id on a <var> tag assigns an identifier to the element.
The identifier must be unique across the page.
Example
An id attribute on a <var> tag.
π r ^2 is the area of a circle.
Using id
The id attribute assigns an identifier to the <var> element.
The id allows JavaScript to easily access the <var> element.
It is also used to point to a specific id selector in a style sheet.
Tip: id is a global attribute that can be applied to any HTML element.
Syntax
Values
| Value | Description |
|---|---|
| identifier | A unique alphanumeric string. The id value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.). |
More Examples
A <var> element with a unique id.
Clicking the button displays the text of the variable element.
how to access element whose id is variable
I need to access elements in html file using javascript, their names are like arr_1 , arr_2 , arr_3 , I wish to use a loop to dynamically create the id then to access them like below:
But it doesn’t work. I remember there is an function to allow me do that, anyone know what that is?
![]()
4 Answers 4
You don’t need the dollar sign preceding document , and you should pass your id variable to the getElementById function, not a string containing ‘id’ :
You might also want to check if getElementById actually found your element before manipulating it, to avoid run-time errors:
Since this question was published and answered quite correctly several times by using document.getElementById(id) , another contender has entered the fray, querySelector , which takes any valid CSS selector and returns the first matched element.
Note that because querySelector takes a CSS selector, selecting an ID requires prefixing the ID with # .
getElementById is typically faster than querySelector (in some browsers, twice as fast), which makes sense, since it doesn’t have to invoke the CSS subsystem to find the element.
However, the option exists, and Stack Overflow is nothing if not thorough when answering questions.
The Difference Between var, let and const in JavaScript and Best Practices

Programming has always included the definition of data, manipulation of data, and finally displaying data. Data can be represented as bits of information that we can alter in computer programs. Since memory locations aren't very human-readable, and change through time — we've started annotating variable data, with human-readable signifiers, which we can call on, to indirectly point to data in-memory.
These signifiers are commonly called variables or reference variables.
Variables are, essentially, pointers or references to some data in a machine's memory, and the pointer can dynamically be changed to reflect the true state of the data we've "labeled".
Note: Commonly and colloquially, it's said that "variables store data" and that they're "containers for data". This is technically incorrect, and stems from a blurred semantic boundary — it's unclear whether people refer to reference variables or objects in-memory. (Reference) Variables are pointers, and they point to objects in the machine's memory — where the data is stored. The colloquial terms are commonplace enough that you'll find them present in documentation, but it's worth keeping object-memory-allocation at least in the back of your head.
Prior to the release of ES2015 (ES6), JavaScript variables were only declared using the var keyword; however, with the introduction of ES6, new ways to declare variables, let and const , were introduced. This oftentimes brings up questions — mainly as to which keyword should be used, and when:
In this guide, we will explore the difference between the three various ways to declare variables in JavaScript — var , let and const , their scopes and when to choose which.
What is Scope in JavaScript?
Scope is an important concept to grasp in order to write code in most programming languages, and plays an important part in choosing which variable keyword you'll want to use. Scope defines variable availability. In JavaScript, we have two scopes: global and local.
- Global Scope: Variables declared outside any code block or function are known as global variables because they have a global scope, and can be referenced from any function or block.
Note: In a JavaScript document, only one global scope exists.
Suppose you have a script file. Again, any variable declared outside any function or block is globally scoped:
In the example above, name is accessible within the logName() function, as it has a global scope. It exists in the context of the application, and the logName() function can call on that context!
- Local Scope: Variables declared within any code block or function are known as local variables, because they have a local scope. They can be referenced only within the code blocks or functions in which they're defined.
This results in:
How come? id is defined — but it isn't defined in the scope of the logId() function. As far as the function is concerned — no id exists. It starts by checking whether there's a locally scoped variable. Since there's none, it checks whether there's a globally scoped variable. If not — id is not defined from the context of logId() !
With the primer/reminder out of the way — let's take a look at how var , let and const depend on the scope, and when each should be used!
The var Keyword in JavaScript
In JavaScript, var is a reserved keyword which is followed by a reference variable name. The name defined after the keyword can then be used as a pointer to the data in-memory.
Using var is the oldest method of variable declaration in JavaScript. Let's declare a variable and initialize it by assigning a value to it using the assignment operator ( = ):
Alternatively, you can break this down into two steps — variable declaration (what it is), and variable initialization (assigning a value to it):
Note: In strongly-typed languages, such as Java, for a long time, you'd define the type of the variable during declaration, and during initialization, you could only assign a value fitting that type. Since Java 10 — a var keyword has been added, which is type-agnostic and infers the type during runtime.
Scope of var
When defined within a function — any var is restricted to that function. When defined outside of a function, a var is global:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
We have two declarations in the preceding example: firstName is globally scoped because it's defined outside a function, and lastName is locally/function scoped because it's defined within a function:
So far so good. However — var has an issue.
The Issue with var
var is not block-scoped. When you declare a variable within a code block, using curly braces ( <> ), its scope "flows out" of the block! For instance:
The name that points to "John Doe" is global, and the name that points to "Daniel Joan" is defined within a block. However, when we try printing the name that's within scope, we run into:
var is not block-scoped. We may think that we've defined a local var name to point to "Daniel Joan", but what we've done in reality is overwrite the var name that points to "John Doe".
Declaring variables using the var declarations everywhere in your code can lead to confusion, overwriting of existing global variables and by extension — bugs, just as we saw in the code snippet.
This is where let and const kick in!
The let Keyword in JavaScript
The let declaration was introduced with ES6 and has since become the preferred method for variable declaration. It is regarded as an improvement over var declarations and is block-scoped (variables that can be accessed only in the immediate block), circumventing the main issue that can arise with using var .
Scope of let
A variable defined with the let keyword has a scope limited to the block or function in which it is defined:
This time around — the firstName referring to "Jane" and the firstName referring to "John" don't overlap! The code results in:
The firstName declared within the block is limited to the block in scope and the one declared outside the block is available globally. Both instances of firstName are treated as different variable references, since they have different scopes.
The const Keyword in JavaScript
The const declaration was introduced with ES6, alongside let , and it is very similar to let . const points to data in memory that holds constant values, as the name implies. const reference variables cannot be reassigned to a different object in memory:
This results in:
Scope of const
The scope of a variable defined with the const keyword, like the scope of let declarations, is limited to the block defined by curly braces (a function or a block). The main distinction is that they cannot be updated or re-declared, implying that the value remains constant within the scope:
Good Coding Conventions
So, what does this all mean, and which should you choose, other than the obvious requirements to avoid bugs? This can actually be boiled down to a couple of good practices:
- const is preferred to let , which is preferred to var . Avoid using var .
- let is preferred to const when it's known that the value it points to will change over time.
- const is great for global, constant values.
- Libraries are typically imported as const .
When importing a library and instantiating it — you don't want to be able to reassign the instance to something else, since you'd enter a slippery slope of "using the library", whereas, something else is "slipping code in" under the hood.
For instance, if you were to require() a library such as Axios, you're conceivably wanting to use its API. However, there's nothing preventing you (or someone else) to switch out the axios instance with something else if you haven't used const to declare it:
By having axios be const — this issue is avoided. Additionally, you can define global constants, which can be used as configuration constants:
Conclusion
In this guide, we've explored the progression of variable declaration in JavaScript, from the original var to the newer let and const .
We've explored Scopes in JavaScript and how the different declaration signifiers affect the scope of a variable in code, noting a glaring issue with using var . Finally, we've explored some good practices, noting when to use which keyword.