In JavaScript, let
is a variable, first appeared in ES2015 (JavaScript Standard). It became one of two variable options to replace var
variables, which were functionally deprecated by that time. The main advantage of let
is that it's visible only within a block of code. This significantly increases code security and helps optimize memory use.
Key characteristics of let variables
1. Declaring a variable begins with a keyword let
plus a unique identifier (name) for the variable.
let SomeIdentifier;
2. For a let
variable identifier, it is forbidden to use JavaScript keywords, e.g. break
, case
, catch
, class
, const
, delete
, do
, else
, function
, if
, return
, var
, etc.
Wrong identifiers:
let if;
let return;
3. In the let
variable you can store strings, numbers, bool, Arrays and Objects.
let text;
text = "words";
4. The name of a let
variable can't start with a number and can include only English alphabet letters, numbers, symbols "$" and "_".
Correct identifiers:
let text;
let TEXT1;
let $text_;
Wrong identifiers:
let 2text;
let #text;
5. It can be initialized within the same line where it was declared.
let text = "story";
6. The values of let
variables can be changed after the initial assignment.
let text = "characters";
text = "words";
7. Scope of let
variables is only within the code block (denoted by curly braces).
If(SomeVariable){
let words = "text";
}
8. let
variables can be of global and functional scope.
let stories = "legends";
If(SomeVariable){
let words = "text";
}
The stories
variable has global scope, while the words
variable has the functional (local) scope.
9. Declaration of the let
variable should be located higher in the code than a value assignment.
Wrong declaration:
texts = "books";
let texts;
10. If let
variables with the same identifier were initialized in global and local scopes, the variable from its local scope takes precedence.
let test;
function Func(){
let test;
}