JAVASCRIPT Tutorial
Scope determines which parts of your code can access variables declared inside a function. Functions create their own scope, meaning variables declared inside a function are not accessible outside of it.
function myFunction() {
let localVariable = "This is a local variable";
}
console.log(localVariable); // Error: localVariable is not defined
const globalVariable = "This is a global variable";
console.log(globalVariable); // This will print "This is a global variable"
In this example, the variable localVariable
has function scope and cannot be accessed outside of the myFunction()
function. The variable globalVariable
has global scope and can be accessed from anywhere in the program.