Why Can You Have Multiple Const Declarations with the Same Name Inside a Loop?

The const keyword in JavaScript is used to declare variables that are intended to remain constant, meaning their values cannot be changed after they are initially set.

// Declaring the same const variable multiple times in the global scope is not allowed and results in an error
const tip = 100;
const tip = 200; // Error: Identifier 'tip' has already been declared

However, you can have multiple const declarations with the same name inside a loop.

// Declaring the same const variable multiple times within a loop is allowed
for (let i = 0; i < 3; i++) {
  const tip = i * 10;
  console.log(tip); // Output: 0, 10, 20
}

In the code above, the const variable tip is being re-declared multiple times.

So, what's going on here? Why is this allowed?

In JavaScript, const and let are block-scoped, meaning they only exist within the block they are declared in. Each iteration of a loop creates a new block scope, so you can declare a new const or let variable with the same name in each iteration.

However, when you declare a const or let variable in the global scope (outside of any function or block), it exists throughout the entire script. If you try to declare another const or let variable with the same name in the global scope, you'll get an error because you're trying to redeclare a variable in the same scope.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda