Understanding Scope in JavaScript
Learn about variable scope in JavaScript and how it affects your code.
What is Scope?
Scope in JavaScript refers to the accessibility of variables, functions, and objects in a particular part of your code during runtime. It determines where variables can be accessed and modified.
Types of Scope
- Global Scope: Variables declared outside any function or block are in the global scope.
- Function Scope: Variables declared within a function are only accessible within that function.
- Block Scope: Variables declared with
let
andconst
within a block (e.g., within curly braces) are only accessible within that block.
Code Example
// let, const, var
let size = 50;
{
let size = 20;
}
// console.log(size); // This will log 50, as the outer size is not affected by the inner block.
function fun1() {
let email = "example@gmail.com";
function fun2() {
let number = 55;
console.log("Your Email:", email); // This will log "Your Email: example@gmail.com"
}
fun2();
}
// fun1(); // Uncommenting this will execute fun1 and log the email.
function myfun3() {
console.log("This is Function 3");
}
// myfun3(); // Uncommenting this will execute myfun3.
const myfun4 = () => {
console.log("This is Function 4");
};
// myfun4(); // Uncommenting this will execute myfun4.
Code Explanation
1. Variable Declarations: let, const, var
The first part of the code demonstrates variable declarations:
let size = 50;
This declares a variable size
in the global scope with a value of 50.
{
let size = 20;
}
Inside the block, a new variable size
is declared with let
. This variable is scoped only to this block. Therefore, the outer size
remains unaffected.
If you uncomment console.log(size);
, it will log 50, as the outer size
is not affected by the inner block.
2. Function Scope
The next part of the code illustrates function scope:
function fun1() {
let email = "example@gmail.com";
function fun2() {
let number = 55;
console.log("Your Email:", email);
}
fun2();
}
In this example, fun1
declares a variable email
that is accessible only within fun1
and its inner function fun2
. When fun2
is called, it can access email
and log it.
If you uncomment fun1();
, it will execute fun1
and log the email.
3. Standalone Functions
The next functions are standalone and can be called independently:
function myfun3() {
console.log(" This is Function 3");
}
This function simply logs a message when called. If you uncomment myfun3();
, it will execute and display the message.
4. Arrow Functions
Lastly, we have an arrow function:
const myfun4 = () => {
console.log("This is Function 4");
};
This arrow function behaves similarly to myfun3
and can also be called independently. Uncommenting myfun4();
will execute it and log the message.