What are scopes in Javascript

Scopes in JavaScript refer to the accessibility or visibility of variables, functions, and objects in some particular part of your code during runtime. It determines where these entities are defined and where they can be accessed.

JavaScript has three types of scopes:

  1. Global Scope: Variables declared outside of any function or block have global scope. They can be accessed from anywhere in the code, including other functions or blocks.
<script>
var globalVariable = "I am a global variable";
function globalFunction() {
console.log(globalVariable); // Accessible from within the function
}
globalFunction(); // Output: I am a global variable
console.log(globalVariable); // Accessible from outside the function
</script>

  1. Local Scope: Variables declared inside a function have local scope. They can only be accessed within that function or any nested functions.
<script>
function localFunction() {
var localVariable = "I am a local variable";
console.log(localVariable); // Accessible within the function
}
localFunction(); // Output: I am a local variable
console.log(localVariable); // Error: localVariable is not defined
</script>

  1. Block Scope: Variables declared with let or const inside a block (e.g., within an if statement or a loop) have block scope. They can only be accessed within that block.
<script>
if (true) {
let blockVariable = "I am a block variable";
console.log(blockVariable); // Accessible within the block
}
console.log(blockVariable); // Error: blockVariable is not defined
</script>

It’s important to understand scopes in JavaScript to avoid variable conflicts, maintain code organization, and ensure proper encapsulation of data.