JavaScript let
Create a variable called carName and assign the value "Volvo" to it:
More examples below.
Description
The let statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called "declaring" a variable:
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
You can also assign a value to the variable when you declare it:
A variable declared without a value have the value undefined .
See Also:
Tutorials:
Syntax
Parameters
| Parameter | Description |
| name | Required. The name of the variable. Variable names must follow these rules: |
More Examples
Use let to assign 5 to x and 6 to y, and display x + y:
Declare many variables in one statement.
Start the statement with let and separate the variables by comma:
Use let in a loop:
Browser Support
let is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
| Chrome | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes |
let is not supported in Internet Explorer 11 (or earlier).

COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Let в javascript что это
Объявление let объявляет локальную переменную с блочной областью действия, опционально инициализируя ее значением.
Try it
Syntax
Parameters
Имена переменных или переменных для объявления.Каждое из них должно быть легальным идентификатором JavaScript.
Для каждой объявленной переменной можно дополнительно указать ее начальное значение в любом легальном выражении JavaScript.
Кроме того, для объявления переменных можно использовать синтаксис назначения деструктурирования .
Description
let позволяет объявлять переменные, которые ограничены областью действия оператора блока или выражения, в котором он используется, в отличие от ключевого слова var , которое объявляет переменную глобально или локально для всей функции независимо от области действия блока. Другое различие между var и let заключается в том, что последний инициализируется значением только тогда, когда синтаксический анализатор оценивает его (см. Ниже) .
Так же , как const let это не создавать свойства window объекта , когда объявлены глобально (в самой верхней области видимости).
Объяснение того, почему было выбрано название « пусть », можно найти здесь .
Многих проблем с переменными let можно избежать, объявив их в верхней части области, в которой они используются (это может повлиять на читабельность).
В отличие от var , let начинается с объявлений , а не операторов . Это означает, что вы не можете использовать одиночное объявление let в качестве тела блока (что имеет смысл, поскольку нет способа получить доступ к переменной).
Examples
Scoping rules
Переменные, объявленные let , имеют свою область видимости в блоке, для которого они объявлены, а также во всех содержащихся подблоках. Таким образом, let работает очень похоже на var . Основное отличие состоит в том, что область видимости переменной var — это вся включающая функция:
На верхнем уровне программ и функций let , в отличие от var , не создает свойства для глобального объекта. Например:
Redeclarations
Повторное объявление той же переменной в пределах той же функции или области действия блока вызывает SyntaxError .
Вы можете столкнуться с ошибками в операторах switch , потому что там только один блок.
Однако,важно отметить,что блок,вложенный внутрь контекстного пункта,создаст новое лексическое окружение,охватывающее блок,что не приведет к показанным выше ошибкам повторного декларирования.
Временная мертвая зона (TDZ)
Говорят , что переменная let или const находится во «временной мертвой зоне» (TDZ) с начала блока до тех пор, пока выполнение кода не достигнет строки, где переменная объявлена и инициализирована.
Находясь внутри TDZ, переменная не была инициализирована значением, и любая попытка доступа к ней приведет к ошибке ReferenceError . Переменная инициализируется значением, когда выполнение достигает строки кода, где она была объявлена. Если при объявлении переменной не было указано начальное значение, оно будет инициализировано значением undefined .
Это отличается от переменных var , которые возвращают значение undefined , если к ним обращаются до их объявления. Код ниже демонстрирует другой результат, когда let и var доступны в коде перед строкой, в которой они объявлены.
Термин «временный» используется потому, что зона зависит от порядка выполнения (времени), а не от порядка, в котором написан код (положение). Например, приведенный ниже код работает , потому что, даже если функция , которая использует let появляется переменная перед переменная объявлена, то функция называется вне ТДЗ.
Протяжен и typeof
Использование оператора typeof для переменной let в ее TDZ вызовет ошибку ReferenceError :
Это отличается от использования typeof для необъявленных переменных и переменных, которые содержат значение undefined :
ТДЗ в сочетании с лексическим скопингом
Следующий код приводит к ReferenceError в показанной строке:
Блок if оценивается, потому что внешняя var foo имеет значение. Однако из-за лексической области видимости это значение недоступно внутри блока: идентификатор foo внутри блока if — это let foo . Выражение (foo + 55) выдает ReferenceError , потому что инициализация let foo не завершена — он все еще находится во временной мертвой зоне.
Это явление может сбивать с толку в следующей ситуации. Инструкция let n of n.a уже находится внутри частной области блока цикла for. Итак, идентификатор n.a преобразуется в свойство ‘ a ‘ объекта ‘ n ‘, расположенного в первой части самой инструкции ( let n ).
Он все еще находится в темпоральной мертвой зоне,поскольку его декларативное заявление не было достигнуто и завершено.
Other situations
При использовании внутри блока let ограничивает область действия переменной этим блоком. Обратите внимание на разницу между var , область видимости которого находится внутри функции, в которой он объявлен.
Однако эта комбинация объявления var и let ниже является SyntaxError из-за того, что var поднимается в верхнюю часть блока. Это приводит к неявному повторному объявлению переменной.
JavaScript Let
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.
Cannot be Redeclared
Variables defined with let cannot be redeclared.
You cannot accidentally redeclare a variable.
With let you can not do this:
Example
let x = «John Doe»;
// SyntaxError: ‘x’ has already been declared
With var you can:
Example
var x = «John Doe»;
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const .
These two keywords provide Block Scope in JavaScript.
Variables declared inside a < >block cannot be accessed from outside the block:
Example
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a < >block can be accessed from outside the block.
Example
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable outside the block:
Example
var x = 10;
// Here x is 10
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
Example
let x = 10;
// Here x is 10
Browser Support
The let keyword is not fully supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support for the let keyword:
| Chrome 49 | Edge 12 | Firefox 44 | Safari 11 | Opera 36 |
| Mar, 2016 | Jul, 2015 | Jan, 2015 | Sep, 2017 | Mar, 2016 |
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
Example
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
With let , redeclaring a variable in the same block is NOT allowed:
Example
var x = 2; // Allowed
let x = 3; // Not allowed
<
let x = 2; // Allowed
let x = 3 // Not allowed
>
<
let x = 2; // Allowed
var x = 3 // Not allowed
>
Redeclaring a variable with let , in another block, IS allowed:
Example
let x = 2; // Allowed
Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.
Meaning: You can use the variable before it is declared:
Example
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with let are also hoisted to the top of the block, but not initialized.
Meaning: Using a let variable before it is declared will result in a ReferenceError :
Example
COLOR PICKER
SUBSCRIBE!
Contacts
If you want to report a bug, as well as make an offer for the site, add an ad or advertisement on the site, do not hesitate to send an email to the admin:
Top Tutorial
Top References
Top Examples
Web Certificates
This site is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
You can also use the Ukrainian version of the site W3Schools українською.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved.
W3Schools is Powered by W3.CSS.
Variables
Most of the time, a JavaScript application needs to work with information. Here are two examples:
- An online shop – the information might include goods being sold and a shopping cart.
- 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.
In older scripts, you may also find another keyword: var instead of let :
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 in the chapter The old "var".
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:
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.
A variable should be declared only once.
A repeated declaration of the same variable is an error:
So, we should declare a variable once and then refer to it without let .
It’s interesting to note that there exist so-called pure functional programming languages, such as Haskell, that 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.
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.
Variable naming
There are two limitations on variable names in JavaScript:
- The name must contain only letters, digits, or the symbols $ and _ .
- 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, each word except 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:
Variables named apple and APPLE are two different variables.
It is possible to use any language, including cyrillic letters, Chinese logograms and so on, like this:
Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we’re writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
There is a list of reserved words, 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:
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.
This is a bad practice and would cause an error in strict mode:
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 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:
- 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.
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.
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 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 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.
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 The old "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.