What is let keyword in JavaScript and How to Use it?

In JavaScript, let is the keyword we use to declare a variable. In 2015, JavaScript’s new version was released that contains several new functions, keywords, parameters, properties, etc. The let keyword is one of them that works in the scope block. Scope block means if you declare a variable inside curly braces { } then it would not work outside the block.

Relation of let keyword with Scope Block

Let’s declare a variable to understand the scope block

let itemCount = 10;

Then if we print itemCount through the console function, we will get the value 10 in the result.

console.log(itemCount);
// output 10

Here, itemCount has a value that is accessible in the same block. Now let’s create a block and then try to access it inside and outside.

if(true){
    let itemCount = 10;
    console.log(itemCount);
    // Output: 10
}
console.log(itemCount);
// Output: Uncaught ReferenceError: itemCount is not defined

In the above example, we have a variable inside an if-statement with an assigned value. Now let’s print through two cases.

In the first case add JavaScript’s built-in function console.log() in the same block. It would print 10 in the browser console because the function is inside the if-statement or in the same scope block.

In the second case add console.log() outside of if-statement that would return the error Uncaught ReferenceError: itemCount is not defined. The reason for this error is JavaScript’s let keyword does not support outer scope blocks, it works only in the same block.

The let Keyword can’t be Redeclared

The let keyword can’t be redeclared, it means once a variable declares with a let keyword then JavaScript wouldn’t allow to redeclare it in the same scope block. Or in simple words, we can’t declare a variable twice using the let keyword in the same scope block. Let’s understand it by the below example

let today = "Monday";
let today = "Tuseday";

In this example, a variable is twice declared and initialized with different values. Now, let’s print it in the browser console.

console.log(today);
Output: Uncaught SyntaxError: Identifier 'today' has already been declared

In the browser console, JavaScript returns the error “Uncaught SyntaxError: Identifier ‘today’ has already been declared” which means JavaScript does not allow redeclaring the today variable.