JS Basic Tutorial
The JavaScript let statement is used to declare a variable. With the let statement, we can declare a variable that is block-scoped. This mean a variable declared with let is only accessible within the block of code in which it is defined.
let
:1) Block Scope:
Variables declared with let are block-scoped, meaning they are only accessible within the block in which they are defined. A block is defined by a pair of curly braces {} (for example, in a function, loop, or conditional statement).
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
2) No Re-declaration:
Unlike var, a variable declared with let cannot be re-declared in the same scope. This helps prevent accidental overwriting of variables.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3) Hoisting:
Variables declared with let are hoisted to the top of their block, but they are not initialized. This means you cannot access a let variable before its declaration—doing so will result in a ReferenceError. This behavior is known as the Temporal Dead Zone (TDZ).
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
4) Reassignable:
Like var, variables declared with let can be reassigned.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>