The scope of a variable refers to the area in the program where the variable can be accessed. Understanding variable scope is crucial to writing efficient, error-free code.
There are three types of variable scopes in JavaScript:
var
let
const
var
Keywordsvar
Keywords were first introduced in 1995 with the initial release of JavaScript. var
has global scope, which means that any part of the program can access the variable. <code class="language-javascript">var x = 10; function inner() { console.log(x); // 输出:10 } console.log(x); // 输出:10</code>
var
will be promoted to the top of the file. This means you can try to access the variable before it's initialized, but the output will be undefined
because we haven't assigned a value to the variable yet. <code class="language-javascript">console.log(x); // 输出:undefined var x = 10; console.log(x); // 输出:10</code>
let
Keywordslet
keyword was introduced in 2015 with the introduction of ECMAScript 6 and provides the functionality of block-level scoping. let
have block scope. Therefore, the variable cannot be accessed in other scopes such as functions or the global scope. var
, accessing a variable declared with let
before declaring it will throw an error due to the Temporal Dead Zone (TDZ). <code class="language-javascript">console.log(x); // 输出:引发错误 let x = 10;</code>
<code class="language-javascript">let x = 10; function inner() { console.log(x); // 输出:引发错误 }</code>
const
Keywordsconst
must be initialized on the same line. <code class="language-javascript">const PI = 3.14; console.log(PI); // 输出:3.14</code>
const
, a TypeError: Assignment to constant variable
error will be thrown at runtime. <code class="language-javascript">const PI = 3.14; PI = 3.5; // 输出:TypeError: Assignment to constant variable.</code>
Happy programming!
The above is the detailed content of Scope of var, let, const. For more information, please follow other related articles on the PHP Chinese website!