Variable Declaration Keyword - let
let
is one of the keywords used to declare variables in JavaScript.
Like var
, it serves to store data but with some important differences.
Variables declared using let
have block-level scope
.
Similar to paragraphs or passages in a book, code also has sections enclosed by curly braces { }
, known as 'blocks'.
let
creates variables that are only accessible within this block.
Basic Usage
You can declare a variable and assign a value using the let
keyword.
Example:
let Variable Declaration
let schoolName = 'Lincoln High School';
In this example, the variable named schoolName
holds the string value 'Lincoln High School'.
Characteristics of let Variables
- Reassignable: Variables declared with
let
can be reassigned to different values.
Reassigning let Variable
let age = 15;
age = 16; // The value of the variable age is changed to 16.
- Block-Level Scope: Variables declared with
let
can only be accessed within the block, and its inner blocks, where it was declared.
Example:
let Variable Block-Level Scope
if (true) {
let message = 'Hello!';
console.log(message); // Outputs 'Hello!'
}
// The message variable cannot be used here.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.