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

前端 未结 4 584
余生分开走
余生分开走 2021-01-06 16:52

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

var is allow duplicate declaration

相关标签:
4条回答
  • 2021-01-06 17:04

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

    0 讨论(0)
  • 2021-01-06 17:08

    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 compilation 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();

    0 讨论(0)
  • 2021-01-06 17:25

    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.

    0 讨论(0)
  • 2021-01-06 17:27

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

    Within the scope of any VariableEnvironment a common 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 讨论(0)
提交回复
热议问题