Javascript offers different methods to create variables. These methods are differentiated by the keywords that are used to declare the variable. These keywords are:
The primary difference in variables declared by each of these keywords is the scope of the variable. The scope of the variable determines the blocks of code in which the variable will be accessible.
A block is a piece of code written within the curly braces, i.e. {}
Each of the above-stated keywords is explained in detail below.
The let
keyword
The variables declared using the let
keyword are block-scoped, i.e., these variables are only accessible within all the child blocks and the block in which they are declared. Once a variable is declared using the let
keyword, it can be read or updated but not declared again.
Code example using the let
keyword
The following snippet of code shows the declaration variables using the let
keyword and their scopes.
The variable x
is declared in the main scope, and it is accessible within the child block of the if
statement.
On the other hand, the variable y
is declared inside the block of the if
statement. Hence its scope is limited. It is not accessible outside the block of the if
statement. That is why the compiler produces an error when we try to print the value of y
outside the if
statement block.