—
### **Variable Scope in JavaScript**
In JavaScript, the scope of a variable determines its accessibility within the code. Based on scope, variables can be classified into **global variables** and **local variables (internal variables)**. Below are their definitions and usage methods:
—
### **1. Global Variables**
Global variables can be accessed from anywhere in the script and are typically defined outside of functions.
#### **Definition:**
“`javascript
// Global variables
var globalVar = “I am a global variable”;
let globalLet = “I am also a global variable”;
const globalConst = “I am still a global variable”;
“`
#### **Characteristics:**
– **Scope:** The entire script file.
– **Lifetime:** From the point of definition until the page is closed.
– **Important Notes:**
– Global variables declared with `var` are attached to the `window` object (in browser environments), which may pollute the global namespace.
– Global variables declared with `let` and `const` are **not** attached to the `window` object.
#### **Example:**
“`javascript
var globalVar = “I am a global variable”;
function test() {
console.log(globalVar); // Can access the global variable
}
test(); // Output: “I am a global variable”
console.log(window.globalVar); // Output: “I am a global variable” (because `var` attaches to `window`)
“`
—
### **2. Local Variables (Internal Variables)**
Local variables can only be accessed within the function or block where they are defined.
#### **Definition:**
“`javascript
function myFunction() {
// Local variables
var localVar = “I am a local variable (var)”;
let localLet = “I am a local variable (let)”;
const localConst = “I am a local variable (const)”;
}
“`
#### **Characteristics:**
– **Scope:** Only accessible within the function or block where they are defined.
– **Lifetime:** From the point of definition until the function or block execution ends.
– **Important Notes:**
– Local variables declared with `var` have function scope.
– Local variables declared with `let` and `const` have block scope (e.g., within `if`, `for` blocks).
#### **Example:**
“`javascript
function myFunction() {
var localVar = “I am a local variable (var)”;
let localLet = “I am a local variable (let)”;
const localConst = “I am a local variable (const)”;
console.log(localVar); // Output: “I am a local variable (var)”
console.log(localLet); // Output: “I am a local variable (let)”
console.log(localConst); // Output: “I am a local variable (const)”
}
myFunction();
console.log(localVar); // Error: localVar is not defined
console.log(localLet); // Error: localLet is not defined
console.log(localConst); // Error: localConst is not defined
“`
—
### **3. Block Scope**
`let` and `const` support block scope, while `var` does not.
#### **Example:**
“`javascript
if (true) {
var blockVar = “I am a block-scoped variable (var)”;
let blockLet = “I am a block-scoped variable (let)”;
const blockConst = “I am a block-scoped variable (const)”;
}
console.log(blockVar); // Output: “I am a block-scoped variable (var)” (`var` does not have block scope)
console.log(blockLet); // Error: blockLet is not defined
console.log(blockConst); // Error: blockConst is not defined
“`
—
### **4. Variable Hoisting**
– Variables declared with `var` are **hoisted** to the top of their scope, but their values are not hoisted.
– Variables declared with `let` and `const` are **not hoisted** and exist in the “Temporal Dead Zone” (TDZ).
#### **Example:**
“`javascript
console.log(hoistedVar); // Output: undefined (due to variable hoisting)
var hoistedVar = “I am a hoisted variable”;
console.log(hoistedLet); // Error: Cannot access ‘hoistedLet’ before initialization
let hoistedLet = “I am not hoisted”;
“`
—
### **5. Best Practices**
1. **Avoid using `var`**
– Use `let` and `const` instead to avoid issues with hoisting and block scope.
2. **Prefer `const` whenever possible**
– Use `const` for values that should not be reassigned to prevent unintended modifications.
3. **Minimize global variables**
– Reduce the use of global variables to avoid polluting the global namespace.
4. **Use modular development**
– Use modules (e.g., ES6 `import`/`export`) to manage variable and function scopes effectively.
—
### **6. Example: Global vs. Local Variables**
“`javascript
// Global variable
const globalVar = “I am a global variable”;
function myFunction() {
// Local variable
const localVar = “I am a local variable”;
console.log(globalVar); // Can access the global variable
console.log(localVar); // Can access the local variable
}
myFunction();
console.log(globalVar); // Can access the global variable
console.log(localVar); // Error: localVar is not defined
“`
—
### **7. Variables in Modular Development**
In modern JavaScript, modules can be used to manage variable scopes efficiently.
#### **Example:**
“`javascript
// module.js
export const moduleVar = “I am a module variable”;
// main.js
import { moduleVar } from ‘./module.js’;
console.log(moduleVar); // Output: “I am a module variable”
“`
—
By following these methods, you can effectively define and manage **global and local variables** in JavaScript.