Skip to main content

JavaScript scopes

In general English, scope means the Opportunity or possibility to do or deal with something.

In JavaScript What is scope?

In Javascript Scope determines the accessibility of the variables:

Types of Scopes:

1.BLock Scopes
2.Function Scope
3.Global Scope

Block Scope:

Before ES6 Javascript has Only two scopes.Tose are Global Scope and Function Scope.

In ES6 introduces two new Javascript Keywords those are let and const.

These Javascript Keywords can be used in Block Scope.

var exampleForScope='below written';

{
    let age='21';
    const name='Shivani'
}
 

In this Above we can see
 Whatever written in blocks we can access with in block only.
Therefore BlockScope means variables can access with in block only not the out side of block.

Function Scope:

Before Knowing function scope we have to Know the what is Local variables.

Local Variables are nothing but variable where we can access variables in local only.

Lets take Random ex:In india we use rupees curency.we can use rupees india only means local.where we will go America there we have to use dollor currency.which means Rupees are not take her.Similarly local variable are.


Variables declared with varlet and const are quite similar when declared inside a function.

They all have Function Scope:

function myFunction(){
    let amount=1000; / function scope : where amount can be accessed in the with in function only.
    var sum=0;  /function scope
    let productNum=2; /function scope
}

Global Scope:

A variable  can defined outside of function becomes a global variable.

a global variable has global scope.

this variable we can access anywhere in the webpage like in With in function,Outside function etc.

var name='shivani';   /global scope
const rollNumber=21;  /global scope
let count=0;         /global scope

Comments