Now when it comes to javascript we have two different types of scopes.
- Global Scope.
- Local Scope.
Now what these scopes mean is basically where we can use variables in our code.
Global Scope:
var number = 20; //Declared globally/root of the code
function calc()
{
return number
}
console.log(calc())
Output:
20
- As you can see the variable number is declared at the root of the code where it can be accessed anywhere within the code.
- Now we wrote a basic function called calc and returned the number variable within it.
- It can get the variable value with ease without any issues.
Local Scope:
function calc()
{
var number = 20;
return number
}
console.log(calc())
Output:
20
- Now here as you can see the variable is declared inside the block of the function and will still be accessible.
- Because we are accessing it via the function name in console.log.
Now, let's try to access it outside the scope of calc function:
function calc()
{
var number = 20;
return number
}
console.log(number)
Output:
ReferenceError: number is not defined
at Object.<anonymous> (C:\Users\arili\Desktop\JS Codes\Functions.js:26:13)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
- Now what we did here is we tried to fetch the number variable which is within from outside the scope of the calc function.
- Now the reason behind this error is that the variable can only be accessed with the scope of the function body either or by calling the calc function itself.
- It's that simple now we call this the local scope.
Verdict:
- So to put it simply global scope will only let you access the variable within its block by calling its function name.
- Whereas local scope is present outside the root of the code where it can be used everywhere.
- Block scoped is something similar to global but here anything other than let, const can be accessed outside the block.
{
let name = "Trinity"
const age = 21
}
//cannot be accessed
{
var name = "neo"
}
//can be accessed
There's another thing about global to it's called Automatically Global so they say:
calc2();
console.log(nameb)
function calc2(){
nameb='ash'
}
Output:
ash
- Here the variable is not declared inside the function so we call upon that function globally outside and as it is without any declaration within the scope body.
- The variable value can be accessed outside as well.
- Log in to post comments