For more tips like this, sign up to the weekly newsletter!

Use blocks to scope block-scoped variables

When you do similar things to several elements, it's easy to accidentally "reuse" an old variable. For example, when you create multiple elements and attach listeners to them, you'll have similar codes:

const btn1 = document.createElement("button");
btn1.addEventListener("click", () => alert("btn1 clicked"));
document.body.appendChild(btn1);

const btn2 = document.createElement("button");
btn1.addEventListener("click", () => alert("btn2 clicked")); // Whops

Did you spot the problem? On the last line, there is a btn1 where it should've been a btn2. This is quite common in similar blocks of code.

How to prevent errors like this?

Use blocks so that previous values are not accessible:

{
  const btn1 = document.createElement("button");
  btn1.addEventListener("click", () => alert("btn1 clicked"));
  document.body.appendChild(btn1);
}

{
  const btn2 = document.createElement("button");
  btn2.addEventListener("click", () => alert("btn2 clicked"));
}

Inside the seconds block, btn1 is not accessible, so there will be an error instead of a silent bug.

What are the block-scoped variables?

Javascript has two variables that are block-scoped: let and const.

var is function-scoped, so a simple block does not limit its scope.

Try it
Learn more: