> 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/accessing-var-before-declaration-gets-undefined.md).

# accessing var before declaration gets undefined❗️

[JS](/web/js.md) ⟩ [variable](/web/js/variable.md) ⟩ [var](/web/js/variable/declare/var.md) ⟩ access before declaration gets "undefined"

{% hint style="danger" %}
(<mark style="color:red;">**unexpected result**</mark>)

[var](/web/js/variable/declare/var.md) <mark style="color:yellow;">**has**</mark>**&#x20;**<mark style="color:red;">**no**</mark> [temporal dead zone](/web/js/variable/access/tdz.md), but <mark style="color:yellow;">**accessing**</mark> it <mark style="color:red;">**before**</mark> its [declaration](/web/js/grammar/declare.md) will <mark style="color:yellow;">**get**</mark> [undefined](/web/js/val/prim/undefined.md), <mark style="color:yellow;">**instead of**</mark> its [initial value](/web/js/variable/declare/initial-value.md) (if exists):exclamation:
{% endhint %}

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

* replit：[access var before declaration](https://replit.com/@pegasusroe/access-var-before-declaration#index.js)

```javascript
// ❗ "var" has no "temporal dead zone", 
//    but it's `undefined` initially.

// ⭐️ access before declaration  ╭── ⭐️ ───╮
log(aVar, typeof aVar);     // ❗ undefined, 'undefined'

// ┌─────────────────┐
// │ var declaration │
// └─────────────────┘

// ⭐️ access after declaration
var aVar = 'hello';

log(aVar, typeof aVar);     // ❗ "hello", 'undefined'
```

{% endtab %}

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

* :white\_check\_mark:[stop using var❗️](/web/js/variable/declare/var/stop-using-var.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).
  {% 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 %}
