How to use 'let' in JavaScript?

In JavaScript, the "let" keyword is used to declare a block-scoped variable. This means that the variable is only accessible within the block in which it was declared. Here's how to use "let" in JavaScript:

let myVariable = "Hello";

In this example, we declare a variable called "myVariable" using "let" and assign it the value of "Hello". Since "myVariable" is declared using "let", it's only accessible within the block in which it was declared. For example, if we declare "myVariable" inside a block (such as an if statement or a loop), it will only be accessible within that block:

if (true) {
  let myVariable = "Hello";
  console.log(myVariable); // Output: "Hello"
// console.log(myVariable); // Error: myVariable is not defined

In this example, we declare "myVariable" inside an if statement block using "let". We can access "myVariable" within the if statement block and output its value to the console. However, if we try to access "myVariable" outside of the if statement block, we'll get an error because "myVariable" is not defined in that scope.

You can also declare and assign multiple let variables at once, like this:

let myVariable1 = "Hello", myVariable2 = 10, myVariable3 = true;

It's important to note that variables declared using "let" can be reassigned a new value. For example:

let myVariable = "Hello";
myVariable = "Goodbye"; // OK, can reassign the value of myVariable

In general, it's a good practice to use "let" when you need to declare a variable that might be reassigned a new value, or when you need block-scoping.