EN
JavaScript - block statement
0 points
In this article, we would like to show you block statement in JavaScript.
xxxxxxxxxx
1
{
2
// Put your code here
3
}
Warning:
The block statement was introduced in ES6 (ES2015).
In this example, we use a block delimited by a pair of braces to group statements. The block is "curly brackets" ({}
) and may optionally be labeled.
xxxxxxxxxx
1
var x = 1;
2
let y = 1;
3
4
if (true) {
5
var x = 2;
6
let y = 2;
7
}
8
9
console.log('x = ' + x); // 2
10
console.log('y = ' + y); // 1
Output:
xxxxxxxxxx
1
x = 2
2
y = 1
Unlike var
statement, identifiers declared with let
and const
do have block scope, which means they are limited in scope to the block in which they were defined.
Example 1
xxxxxxxxxx
1
let x = 1;
2
{
3
let x = 2;
4
}
5
6
console.log(x); // 1
Example 2
xxxxxxxxxx
1
const c = 1;
2
{
3
const c = 2;
4
}
5
6
console.log(c); // 1