Home >Web Front-end >JS Tutorial >Definition on global scope and local scope

Definition on global scope and local scope

Barbara Streisand
Barbara StreisandOriginal
2025-01-23 20:49:42339browse

Definition on global scope and local scope

Scope in JavaScript determines the visibility and accessibility of variables. There are two main scopes:

Global scope:

  • Variables declared outside any function or block of code have global scope.
  • These variables can be accessed from anywhere in the code.
  • In general, overuse of global variables is bad programming practice because they make code difficult to maintain and debug.

Local scope:

  • Variables declared inside a function or code block have local scope.
  • These variables can only be accessed within that function or block of code.
  • Local variables are created when the function is called and destroyed when the function returns.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn