DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

How JavaScript Blocks work 🧱

A block in JavaScript is used to group zero or more statements with curly braces ({}). Remember that a statement is simply a unit of code that does something or produces some behavior.

Blocks are most often used with while, if...else and for statements. We've all seen this, however, there is an interesting implication when using blocks with let and const.

In non-strict mode, functions and var variables do not have block scope:

var foo = 'yo';
{
  var foo = 'hey';
}

console.log(foo); // Logs 'hey'
Enter fullscreen mode Exit fullscreen mode

But when using let or const, blocks will hold the scope of each variable:

let foo = 'yo';
{
  let foo = 'hey';
}

console.log(foo); // Logs 'yo'
Enter fullscreen mode Exit fullscreen mode
const foo = 'yo';
{
  const foo = 'hey';
}

console.log(foo); // Logs 'yo'
Enter fullscreen mode Exit fullscreen mode

Note that no SyntaxError is thrown in the const example for a duplicate declaration. This is because the foo variable inside the block is contained within its own scope and thus does not conflict with the outer scope.

We use blocks so much in JavaScript that sometimes it's easy to forget their concept. They often seem attached to their adjacent code such as an if statement or function. But as we've seen in the example above, you can create perfectly valid code with your own isolated blocks if you want:

{
  console.log('I run inside my very own block!');
}
Enter fullscreen mode Exit fullscreen mode

Although this looks strange (almost as if you're creating an object on the fly), it's 100% valid. Blocks are fun! 🧱


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (0)