Variable Declaration Keyword - let
let
is a keyword used in JavaScript to declare variables.
Similar to var
, it creates variables that store data and can be reassigned. However, variables declared with let
have block-level scope
.
Block-level scope
means that the variable is accessible only within the block of code enclosed by curly braces.
For instance, if we replace var
with let
in the example code from the previous lesson, it would look like this:
if (true) {
let name = "one";
}
console.log(name); // ReferenceError: name is not defined
In the code above, the name
variable declared with let
is accessible only within the if
block.
Trying to access the name
variable outside the conditional statement block composed of if
will result in a ReferenceError
.
As such, variables declared with let
possess block-level scope, meaning they can only be accessed within the block.
Reassignable let Variables
A variable declared with let
can be reassigned to a different value after its initial declaration.
let number = 10;
number = 20; // The value of the variable number is changed to 20
console.log(number); // 20
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.