JavaScript scope refers to the visibility and accessibility of variables within different parts of a program. Variables declared inside a function or a block of code have local scope, which means they can only be accessed within that function or block. Variables declared outside of a function or block have global scope, which means they can be accessed from any part of the program.
Let’s take a look at an example to better understand this concept:
let globalVar = "I am a global variable";
function myFunction() {
let localVar = "I am a local variable";
console.log(localVar); // Output: "I am a local variable"
console.log(globalVar); // Output: "I am a global variable"
}
myFunction();
console.log(globalVar); // Output: "I am a global variable"
console.log(localVar); // Output: Uncaught ReferenceError: localVar is not defined
In this example, globalVar
is declared outside of the function and has global scope, so it can be accessed from both inside and outside of the function. localVar
, on the other hand, is declared inside the function and has local scope, so it can only be accessed within that function. When we try to access localVar
outside of the function, we get a reference error because it is not defined outside of the function.
It’s important to note that if a local variable has the same name as a global variable, the local variable will take precedence within the scope of the function or block it is declared in. Let’s see an example:
let myVar = "I am a global variable";
function myFunction() {
let myVar = "I am a local variable";
console.log(myVar); // Output: "I am a local variable"
}
myFunction();
console.log(myVar); // Output: "I am a global variable"
In this example, myVar
is declared both globally and locally within the function. When we call myFunction()
, the local myVar
takes precedence and is logged to the console. Outside of the function, the global myVar
is accessed and logged to the console.
Understanding scope is crucial when writing JavaScript code, as it helps prevent naming conflicts and ensures that variables are accessed and manipulated correctly throughout the program.