DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

5 1

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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay