Are JavaScript let and const Variables Block-Scoped?

Find out if const and let are block-scoped in JavaScript

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.