Skip to main content

Block

A block is used to group statements. The block is bound by a pair of curly braces ({}).

Syntax

{
statements;
}

Work out

var a = 5;
let b = 10;
{
var a = 7;
let b = 20;
}
console.log(a);
// expected output: 7
console.log(b);
// expected output: 10

Examples

Variable declaration using var

Block is not applicable for variables declared using the var keyword as they are function-scoped.

var a = 10;
{
var a = 20;
}
console.log(a);
// expected output: 20

Variable declaration using let

Block is applicable for in case of let keyword as they are block-scoped.

let x = 12;
{
let x = 16;
}
console.log(x);
// expected output: 12

Variable declaration using const

Block is applicable for variables declared using the const keyword. Here we declare the same variable with const keyword. Since the second variable declared inside the block will be accessible only within the scope of that block.

const z = 50;
{
const z = 65;
}
console.log(z);
// expected output: 50
const z = 50;
{
const z = 65;
console.log(z);
}
// expected output: 65
Note

Based on the application use following keywords, because there may be a chance for data manipulation if not used correct one.