最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does var allow duplicate declaration but why does const and let not allow duplicate declaration? - Stack Overfl

programmeradmin3浏览0评论

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?

var is allow duplicate declaration

xx=1;
xx=2;
console.log(xx+xx);//4

var xx=1;
var xx=2;
console.log(xx+xx);//4

 

Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?

var is allow duplicate declaration

xx=1;
xx=2;
console.log(xx+xx);//4

var xx=1;
var xx=2;
console.log(xx+xx);//4

 

But let and const does not allow duplicate deceleration

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 saw something about that in here like,

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.

But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?

Share Improve this question edited Mar 13, 2018 at 6:42 Ramesh Rajendran asked Mar 7, 2018 at 9:15 Ramesh RajendranRamesh Rajendran 38.7k49 gold badges157 silver badges238 bronze badges 6
  • Why what? Why let doesn't allow redeclaration? Or why var does? – Sergio Tulentsev Commented Mar 7, 2018 at 9:16
  • 1 because const does what its name says, it is constant. – Wreigh Commented Mar 7, 2018 at 9:17
  • What kind of answer are you looking for? – gurvinder372 Commented Mar 7, 2018 at 9:17
  • Let is scope sensitive, var isn't. I assume this choice was made to force js user to not fall into bad pratices. – Alexandre Nicolas Commented Mar 7, 2018 at 9:18
  • 2 var is an old thing. let and const where introduced so JS code is more strict with less unexpected behavior. If you try to redeclare it, it's not a normal behavior. Either you pick an other identifier, or you change the value (if it's not a const). Or you split your code into two functions because you have too much code lines in this one. It help thinking about your own code. – Kulvar Commented Mar 7, 2018 at 9:18
 |  Show 1 more ment

4 Answers 4

Reset to default 11

var

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);
  • Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.

let and const

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']

Why Does it Matter?

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 remend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.

Unlike var, let is an ES2015 specification. The specification says:

Redeclaring the same variable within the same function or block scope raises a SyntaxError.

This is to improve scoping over vanilla var.

why does const and let not allow duplicate declaration?

There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a pilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.

function checkLetDuplication() {
  let i = 'function scope';
  for ( let i = 0 ; i < 3 ; i++ )
  {
    console.log('(for statement scope): inside the for loop i, equals: ', i);
  }
  console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();

Assuming you want to know whether this behavior is as per spec, check this 13.3.2

Within the scope of any VariableEnvironment a mon BindingIdentifier may appear in more than one VariableDeclaration but those declarations collective define only one variable.

let and const are the recent editions, while var is probably as old as Javascript itself.

In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论