What is the reason behind var allowing duplicate declaration while const and let do not?
var
allows for duplicate declarations:
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
However, let
and const
do not allow for duplicate declarations:
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I came across an explanation on this page which states,
Assuming strict mode,
var
will let you re-declare the same variable in the same scope. On the other hand,let
will not.
But why exactly do let
and const
not allow re-declaration? And why does var
behave differently? How does JavaScript manage these three types of declarations?