Home >Web Front-end >JS Tutorial >Definition on global scope and local scope
Scope in JavaScript determines the visibility and accessibility of variables. There are two main scopes:
Global scope:
Local scope:
Example:
<code class="language-javascript">// 全局变量 let globalVar = "我是全局变量"; function myFunction() { // 局部变量 let localVar = "我是局部变量"; console.log(localVar); // 输出: "我是局部变量" console.log(globalVar); // 输出: "我是全局变量" } myFunction(); console.log(localVar); // 错误:localVar 未定义 console.log(globalVar); // 输出: "我是全局变量"</code>
In this example, globalVar
is a global variable and therefore can be accessed both inside and outside myFunction
. localVar
is a local variable, so it can only be accessed inside myFunction
.
Understanding scope is crucial to writing concise and maintainable code. Using local variables when possible avoids naming conflicts and makes the code easier to understand.
The above is the detailed content of Definition on global scope and local scope. For more information, please follow other related articles on the PHP Chinese website!