본문으로 건너뛰기

Variable Declaration Keyword - let

Variable Declaration Keyword - let

let is one of the keywords used for declaring variables in JavaScript.

It serves a similar purpose to var in storing data, but there are a few important differences.

Variables declared with let have block-level scope.

Just like paragraphs or sections you come across when reading a book, there are parts in the code enclosed with curly braces { }, which are referred to as 'blocks'.

let creates variables that are only usable within these blocks.


Basic Usage

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

Example:

let schoolName = 'Seoul High School';

In this example, a string value 'Seoul High School' is stored in the variable named schoolName.


Features of let Variables

  1. Reassignable: Variables declared with let can be reassigned to different values.
let age = 15;
age = 16; // The value of the variable age is changed to 16.

  1. Block-Level Scope: Variables declared with let are accessible only within the block in which they are declared, and any sub-blocks contained within.

Example:

if (true) {
let message = 'Hello!';
console.log(message); // Outputs 'Hello!'
}

// The variable message cannot be used here.