JavaScript Let - What is Let in JavaScript



JavaScript Let

  • The let keyword was introduced in ES6 (2015).
  • Variables defined with let cannot be redeclared.
  • Variables defined with let must be declared before use.
  • Variables defined with let have Block Scope.

Cannot be Redeclared

  • Variables defined with let cannot be redeclared.
  • You cannot accidentally redeclare a variable.
  • With let you can not do this.
let x = "John Doe";
let x = 0;
// SyntaxError: 'x' has already been declared

Block Scope

  • Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
  • ES6 introduced two important new JavaScript keywords: let and const.
  • These two keywords provide Block Scope in JavaScript.
  • Variables declared inside a { } block cannot be accessed from outside the block:
{
  let x = 2;
}
// x can NOT be used here

Redeclaring Variables let

  • Redeclaring a variable using the let keyword can solve this problem.
  • Redeclaring a variable inside a block will not redeclare the variable outside the block.
javascript-redeclare-variable

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>Redeclaring a Variable Using let</h2>

<p id="demo"></p>

<script>
let  x = 10;
// Here x is 10
{  
let x = 2;
// Here x is 2
}

// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Output

Redeclaring a Variable Using let
10

Related Searches to JavaScript Let - What is Let in JavaScript