Are JavaScript let and const Variables Block-Scoped?

In JavaScript, variables declared using let or const are block-scoped, where:

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.