var
is allow duplicate declaration
The var
keyword was the only way to define variables until 2016*.
No matter where you write var x
, the variable x
is treated as if it were declared at the top of the enclosing scope (scope for var
is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name
with fenton
, and add Fenton
to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
var
keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.Both let
and const
are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const
keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x
, you have to write const x = 'Fenton'
) - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
If you want to avoid some of the more confusing aspects of var
, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const
and let
keywords.
I recommend using const
as your default keyword, and upgrade it to let
only in cases where you choose to allow re-assignment.