JavaScript Scopes

Defination:-
Scope:-Scope defines a boundary, within that boundary you can access variables , If you try to access that variable outside the boundary, an error will occur.
Scopes tell us where our variables and functions will be accessible to us.There will be some place where we will be able to read the variable and call our functions.But there will be some places where you will not be able to call and access variables and functions.Means if you try to call or access there then javascript will give error.

Three types of Scope :-
- Block Scope
- Function Scope
- Globle Scope
1 . Block Scope :- If we make variables from const and let then it is in block scope.
- ES6 introduced two important new javaScript keyword : let and const.
- These two keyword provide Block scope in javascript.
- Declared inside a { } block can't be accessed from outside the block.
And If we want to access the let and const variables outside the block scope then it will give us the referenceError.
Examples :-
function foo(){
if (true){
var fruits ="apple"; // exist in function scope
let fruits2= "banana"; // exist in block scope
}
console.log(fruits)
console.log(fruits2)
}
foo();
//apple
// error : fruits2 is not defined
2 . Globle Scope :- Globle scope variables are those which we can access anywhere. And the scope they have is called global scope.
- The outside all the functions is considered the globle and the variable defined inside the globle scope can be accessed and alterd in any other scopes.
let MyName="Nikhil";
// MyName
function MyFunc(){
// MyName
}
3 . Function Scope :- The scope inside any function is called function scope.If we define any variable inside the function and access that variable inside the function itself then it will be accessible, But if we try to access it outside the function scope it will give us ReferenceError.
- Each function create a new scope.
- Variables defined inside a function are not accessible from outside the function.
function name (){
var age :22;
console.log(age);
}
name() // 22
console.log(age) // error




