/

HTML / CSS / JavaScript Tutorial

JavaScript Statement: let

[this page | pdf | back links]

In JavaScript, the let statement declares a variable with ‘Block Scope’.

 

Prior to ECMAScript 2015, variables could only be declared using the var statement, see here. The var statement defined the variable either globally (outside any function), i.e. with ‘Global Scope’, or locally within a function, i.e. with ‘Function Scope’. In contrast, a let statement defines the variable within a given block, i.e. within a matching { and }.

 

The variable value with ‘Block Scope’ inside the block cannot be accessed from outside the block. If the same variable has apparently been declared before the block starts, then the variable returns to having that value after the block finishes.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting values of <code>x and y</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
document.getElementById("Example").innerHTML =
  'let i = 0;<br>var x = 0;<br>for (let i = 1; i < 4; i++) { x += i; }<br>x += i;'
  + '<br>var j = 0;<br>var y = 0;<br>for (var j = 1; j < 4; j++) { y += j; }<br>y += j;'
  + '<br>// x is (1 + 2 + 3) + 0 = 6 but y is (1 + 2 + 3) + 4 = 10'

let i = 0;
var x = 0;
for (let i = 1; i < 4; i++) { x += i; }
x += i;
var j = 0;
var y = 0;
for (var j = 1; j < 4; j++) { y += j; }
y += j;
// x is (1 + 2 + 3) + 0 = 6 but y is (1 + 2 + 3) + 4 = 10

document.getElementById("Result").innerHTML = "x = " + x + ", y = " + y;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words


Desktop view | Switch to Mobile