5

Why am I able to declare a var multiple times? I would expect an error.

This code raises an error:

let a = true;
let a = false;

Uncaught SyntaxError: Identifier 'a' has already been declared

Why doesn't this raise an error too?

var b = true;
var b = false;

Expected: Uncaught SyntaxError: Identifier 'b' has already been declared

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
user332336
  • 81
  • 5
  • Related: [Declaring a Javascript variable twice in same scope - Is it an issue?](https://stackoverflow.com/questions/21726948) – adiga Feb 19 '19 at 07:39

2 Answers2

5

It's because there's variable hoisting with var, but not with let (or const for that matter).

So that means that each time you use var, it'll essentially cancel out the previous operations because to the JavaScript interpreter, your first code looks like:

var b;
b = true;
b = false;

But this doesn't work with let or const because let and const are block scoped, whereas var is function scoped.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

var gets hoisted; duplicate variable names are ignored. To the interpreter, your second snippet looks like:

var b;
b = true;
b = false;

In contrast, let is not hoisted, so duplicate declarations are forbidden.

Snow
  • 3,820
  • 3
  • 13
  • 39
  • 3
    *"let is not hoisted*" isn't correct. All declarations (`var`, `let`, `const`, `function`, `function*`, `class`) are hoisted in javascript https://stackoverflow.com/a/31222689/3082296 – adiga Feb 19 '19 at 07:37