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

前端 未结 4 621
余生分开走
余生分开走 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: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();

提交回复
热议问题