In JavaScript, variables declared using let or const are block-scoped, where:
- A block is defined by curly braces (
{}); - A block is used to group multiple statements together;
letandconststatements are local to their containing block;letandconstcannot be shadowed in their local scope.
It has the following syntax:
{
// ...
}
Blocks are commonly used with functions, conditionals (such as if...else, switch, try...catch, etc.), loops (such as for, while, etc.), and so on.
For example:
const foo = 1;
{
const foo = 2;
}
console.log(foo); // 1
In the code above, the block-scoped constant (i.e. const foo = 2) is local to its containing block and can be declared uniquely within its block, which is why it does not throw a "SyntaxError: Identifier 'foo' has already been declared" exception.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.