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
Which of the following correctly describes the characteristics of the let
keyword?
The variable's value cannot be changed.
The declared variable is accessible from anywhere.
The variable has block-level scope.
An initial value must be assigned when declaring a variable.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result