JavaScript

What is the let Keyword in JavaScript

In JavaScript, there are multiple keywords available that are utilized to declare the variable in a program, such as “var”, “let”, and “const”. More specifically, the “let” keyword is used to initialize the variable in different forms, like globally, within the defined function, or in multiple code blocks in a program.

In this tutorial, we will demonstrate the let keyword in JavaScript.

What is the “let” Keyword in JavaScript?

The “let” keyword in JavaScript is used for declaring the variable to perform operations.

To utilize the let keyword to initialize the variable for further, use the following syntax:

let variable_name = value;

Here:

  • let” is a keyword used to define a variable.
  • variable_name” indicates the name of the variable that is declared.
  • value” defines the variable value.

How to Use the “let” Keyword in JavaScript?

To use the let keyword, there multiple methods can be utilized. Some of them are listed below:

Method 1: Declaring Variable in Global Scope

When a variable is initialized outside of the function and can be accessed anywhere in the program is called the global scope of the variable.

Example

First, create a global variable using the “let” keyword:

let number=20;

Invoke the “console.log()” method and pass the argument to display its value on the console:

console.log(number);

Define a function where we will access the global variable “number”:

function num(){

  console.log(number);

}

Now, call the defined function “num()”:

num();

Method 2: Declaring Variable in Function Scope

When the variable is declared within a function and can only be accessed in the function is known as the function scope. Users can declare the variable globally as well as locally.

Example

In this stated example, first, define a function with a particular name and declare a variable with the help of the “let” variable:

let number=20;

function num(){

  let number=49;

  console.log(number);

}

num();

console.log(number);

Method 3: Redeclaring Variables in Different Blocks

You can also declare the variable in different code blocks. To do so, first, declare the variable globally and then declare it in a different block. However, the inner block will execute first and then outer or globally declare a variable:

let a=21;

Then, initialize another variable using the “let” keyword within the block:

{

  let a=211;

  console.log(a);

}

console.log(a);

That’s all about the let keyword in JavaScript.

Conclusion

The “let” keyword in JavaScript is utilized for declaring the variable. We can declare the variable with different scopes, including “Global Scope”, and “Function Scope”, and declare the variable in multiple blocks in a single code. This tutorial has demonstrated the let keyword in JavaScript with multiple methods.

About the author

Hafsa Javed