EN
JavaScript - block statement
0
points
In this article, we would like to show you block statement in JavaScript.
Syntax
{
// Put your code here
}
Warning:
The block statement was introduced in ES6 (ES2015).
Practical example
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.
// ONLINE-RUNNER:browser;
var x = 1;
let y = 1;
if (true) {
var x = 2;
let y = 2;
}
console.log('x = ' + x); // 2
console.log('y = ' + y); // 1
Output:
x = 2
y = 1
Block scope
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
// ONLINE-RUNNER:browser;
let x = 1;
{
let x = 2;
}
console.log(x); // 1
Example 2
// ONLINE-RUNNER:browser;
const c = 1;
{
const c = 2;
}
console.log(c); // 1