let is a javascript keyword used to declare a variable, it is introduced by ECMAScript 2015(ES6) in 2015. Variable declared with let has block scope, it means these variables are only accessible inside a block where they are declared.

  1. Variable declared with let cannot be redeclared.
  2. Value can be reassigned to variable declared with let keyword.
  3. Variable should be declared with let before use.
  4. Variable initialization is optional.

Declaring variable with let

Syntax

let variable_name;

Example

let variable with Global Scope

<script>
let speed;
</script>

let variables have block scope, but if the variable is declared with let outside block or function, it can be accessed anywhere in the script.

let variable with Block Scope

<script>
{
  let speed;
}
</script>

Here, curly braces represents block, and variable speed is declared inside it. So, it is only accessible inside the block.

Redeclaring variable with let

In javascript, variable declared with let cannot be redeclared.

<script>
let speed = 30;
let speed = 50; // Error: variable cannot be redeclared
</script>

Declaring variable with let with initializer(value)

<script>
let speed =  20;
</script>

Variable speed is assigned a value 20 using assignment operator = (equalsto). When value is assigned during declaration, that value is called initializer.

Declaring variable with function scope

<script>
function distance()
{
        //function scope
	let km = 20;
	document.write(km); //  outputs 20
}
distance();
document.write(km); // Error, because km has function scope
</script>

Variable km is declared inside function, so it has function scope. Hence, it is only accessible inside the function. Accessing outside function throws error.

Declaring variable with function and Global scope

<script>
//Global scope
let km = 30;
function distance()
{
        //function scope
	let km = 20;  
	document.write(km); // outputs 20
}
document.write(km); // outputs 30
 distance();
</script>

Variable km is declared inside function and outside function as well. So, both variables km has different scope, one has global scope and another has function scope.

Variable declared with Global scope only

<script>
//Global scope
let km = 30;
function distance()
{
	km = 20; // value reassigned
	document.write(km); // outputs 20
}
document.write(km); // outputs 30
 distance();
</script>

Variable km is declared outside function, so it has global scope and again value is reassigned inside function distance(). Hence, variable km is accessible through out the program.