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:
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
- Method 2: Declaring Variable in Function Scope
- Method 3: Redeclaring Variables in different blocks
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:
Invoke the “console.log()” method and pass the argument to display its value on the console:
Define a function where we will access the global variable “number”:
console.log(number);
}
Now, call the defined function “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:
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:
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.