JS Bits with Bill
JS Bits with Bill

JS Bits with Bill

How JavaScript Blocks work 🧱

How JavaScript Blocks work 🧱

JS Bits with Bill's photo
JS Bits with Bill

Published on Sep 9, 2020

2 min read

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'

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'
const foo = 'yo';
{
  const foo = 'hey';
}

console.log(foo); // Logs 'yo'

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!');
}

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!

 
Share this