> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/variable/declare/var/in-block-cant-shadow.md).

# var has no block scope❗️

[JS](/web/js.md) ⟩ [variable](/web/js/variable.md) ⟩ [var](/web/js/variable/declare/var.md) ⟩ has no block scope

{% hint style="danger" %} <mark style="color:purple;">**var in block**</mark> <mark style="color:red;">**doesn't**</mark>**&#x20;**<mark style="color:yellow;">**have**</mark> [block scope](/web/js/grammar/statement/other/block/block.md), <mark style="color:red;">**cannot**</mark>**&#x20;**<mark style="color:yellow;">**shadow**</mark> [let](/web/js/variable/declare/let.md) variable in the <mark style="color:yellow;">**outer enclosing scope**</mark>.
{% endhint %}

{% tabs %}
{% tab title="👥 相關" %}

* [variable shadowing](/web/js/variable/shadow.md)
* [var in block can't shadow outer let❗️](/web/js/variable/declare/var/var-in-block-cant-shadow-outer-let.md):exclamation:
* [var hoisting](/web/js/scope/hoist/variable/var.md) - [var](/web/js/variable/declare/var.md) is hoisted to top of enclosing [function scope](/web/js/scope/function.md).
* [let redeclaration not allowed even in sloppy mode❗️](/web/js/variable/declare/let/no-redeclare.md) - [let](/web/js/variable/declare/let.md) doesn't allow [redeclaration](/web/js/variable/declare.md).
  {% endtab %}

{% tab title="💈範例" %}

* replit：[var in block can't shadow outer let](https://replit.com/@pegasusroe/let-doesnt-allow-redeclaration-1#index.js)
* 👉 [⛔️ SyntaxError](/web/js/err/syntax.md) ⟩ [identifier 'xxx' has already been declared❗️](/web/js/err/syntax/redeclare.md)

```javascript
function f() {
    
    let a = 1;       // let declaration
    
    // var a = 2;    // <----- var declaration is hoisted here❗️
                     //        which raises a redeclaration SyntaxError.
                     // (let doesn't allow redeclaration)
    
    // block scope
    {
        // ⭐️ `var` doesn't have block scope, 
        //     cannot shadow `let` variable in outer enclosing scope.
        var a = 2;
        //  ^
        // ⛔ SyntaxError: Identifier 'a' has already been declared
    }
    
    // another block
    {
        let b = 3;

        // ❗ although `var` doesn't have "block scope", 
        //    we can't put let/var in the same block either.
        var b = 4;
        //  ^
        // ⛔ SyntaxError: Identifier 'b' has already been declared
    }
    
}
```

{% endtab %}

{% tab title="📘 手冊" %}

* [ ] [Statements and declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements) ⟩ [declaring variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements#declaring_variables) ⟩ [var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
  {% endtab %}
  {% endtabs %}
