Javascript - Block Scope (let and const)
📖 Read the lesson
Code Life
By Pierre Marsaa
Variables Inside a Block
Functions are not the only places that create their own scope. Every pair of curly braces
{ }
in an
if
statement or a loop creates a
block
.
When you declare a variable with
let
or
const
inside a
{ }
block, it only exists
inside that block
. Trying to read it outside throws an error:
↗️
Loading editor...
↶
▶️ Run
↷
This rule is called
block scope
: variables declared with
let
or
const
stay locked inside the
{ }
curly braces where they were created.
Verify