Skip to main content
Practice

Variable Declaration Keyword - let

let is a keyword in JavaScript used to declare variables.

It serves the same purpose as var in storing data but has some crucial differences.

A variable declared with let has block-level scope.

Much like paragraphs or sections you encounter when reading a book, code also has portions enclosed in curly braces { }, which are referred to as 'blocks'.

let creates variables that are only accessible within that block.


Basic Usage

You can declare a variable and assign a value using the let keyword.

Example:

Declaring a variable with let
let schoolName = 'Greenwich High School';

In this example, a variable named schoolName is storing the string value 'Greenwich High School'.


Features of let Variables

  1. Reassignable: A variable declared with let can be reassigned to a different value.
Reassigning a let variable
let age = 15;
age = 16; // The value of the variable age is now 16.

  1. Block-Level Scope: A variable declared with let is only accessible within the block where it is declared and its inner blocks.

Example:

Block-Level Scope of let
if (true) {
let message = 'Hello!';
console.log(message); // 'Hello!' printed.
}

// The message variable cannot be used here.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.