Scope is an important concept to understand how variables and functions are accessed and used in your code. Scope determines the visibility and accessibility of variables, while helping to avoid conflicts and errors in the code.
There are 2 main types of scope:
Global scope can be accessed from anywhere in the JavaScript code. When you declare a variable outside of any function, it automatically becomes a global variable.
var globalVariable = "I am a global variable";
function foo() {
console.log(globalVariable);
}
foo(); // Output: "I am a global variable"
Function scope only applies to variables declared within the same function. These variables can only be accessed from within that function.
function foo() {
var functionVariable = "I am a function variable";
console.log(functionVariable);
}
foo(); // Output: "I am a function variable"
console.log(functionVariable); // Error: functionVariable is not defined
Block scope applies to variables declared within a code block, such as a loop or a conditional statement. These variables can only be accessed from within that code block.
function foo() {
if (true) {
var blockVariable = "I am a block variable";
console.log(blockVariable);
}
}
foo(); // Output: "I am a block variable"
console.log(blockVariable); // Error: blockVariable is not defined