In the world of JavaScript programming, the concept of "scope" is one of the key and fundamental concepts that you need to understand. Basically, scope tells us where variables and functions are accessible and in which contexts they can be used.
Generally, JavaScript has two main types of scope: global scope and local scope. Variables that are defined outside of any function are in the global scope, meaning they can be accessed anywhere in the code. In contrast, variables defined within a function are in the local scope of that function and can only be accessed within that function.
Since ECMAScript 6, we have also observed the introduction of block scope, which allows variables to be defined using the `let` and `const` keywords. This means that developers can create more precise variables and manage related issues better, as well as prevent common pitfalls related to accessing inappropriate variables. Below is an example of this concept using practical code.
<script>
// Global scope variables
var globalVar = 'I am a global variable';
function localScopeDemo() {
// Local scope variables
var localVar = 'I am a local variable';
console.log(localVar); // Accessible within the function
}
localScopeDemo();
// Attempting to access local variable outside of function
console.log(localVar); // Error: localVar is not defined
// Using block scope
if (true) {
let blockVar = 'I am a block variable';
console.log(blockVar); // Accessible within the block
}
// Attempting to access block variable outside of block
console.log(blockVar); // Error: blockVar is not defined
</script>
Line by Line Explanation
var globalVar = 'I am a global variable';
Here we define a global variable called
globalVar
that is accessible anywhere in the code.function localScopeDemo() { var localVar = 'I am a local variable'; }
We have a function named
localScopeDemo
, which defines a local variable localVar
within it. This variable can only be used within that function.console.log(localVar);
Inside the function, we print the value of the local variable
localVar
; this action is possible within the function.console.log(localVar);
When trying to access the local variable outside of the function, we encounter an error because it is not accessible outside its defined scope.
if (true) { let blockVar = 'I am a block variable'; }
Here, we define a block variable
blockVar
inside an if
block, which can only be accessed within that same block.console.log(blockVar);
Outside of the
if
block, attempting to access the block variable blockVar
results in an error since it is not defined outside the scope of its block.