Scoping in JavaScript

Scoping in JavaScript

Scoping - Definition,Types ,Lifetime

Scope refers to the availability/accessibility of variables.

For illustration, suppose we have two scopes that are given below.

//their scope
{
//your scope
}

In general, if a variable defined inside your scope , you can’t access it outside their scope. But your scope can access elements defined outside of it i.e in their scope

Three types of scopes exist in JavaScript:

  • Block Scope

  • Function Scope

  • Global Scope

Block Scope

{
    let a =10
}
console.log(a) //accessing variable a outside of its scope

The above example will throw an error

You can access outside scope elements from inside scope but the reverse is not true.

But if we use `` var``` keyword


### Local Scope:

If we use declare a variable inside a function in JavaScript , then  the variable created has a local scope. Also any parameters defined in function protoype are also Local.

```jsx
function abc(){
    let name="Saurav" // it has local scope
}
console.log(name) // throw an error outside local scope

Function Scope:

Variables declared inside a function are not accessible from outside the function.

function abc(){
    let a="Saurav"
    var b="is"
    const c="a learner"
}
console.log(a) //error
console.log(b) //error
console.log(c) //error

{
    var d= "Not throw any error in case of var keyword in Block Scope";
    let e= "throws error as we used let or const "
}
console.log(d) // no error

console.log(e) // throws error

Global Scope:

Variables created in this scope can be accessed anywhere inside the script.

let a =1;
{
    console.log(a) //not throws any error
}

Do it yourself with ``` var & const


If you don’t declare variable with any keyword(const,let,var) but initialize them with a value, they will be automatically declared as a global variable.

```jsx
let a =1;
{
    b=2
    console.log(a) //not throws any error
}
console.log(b) //prints 2

But in the case of functions, you also need to call the function to make it work

//without calling function
console.log(name) //throws error

function abc(){
    name="Saurav"
}
//with calling function
abc()
console.log(name) //no error

function abc(){
    name="Saurav"
}

All modern browsers support running JavaScript in ``` Strict Mode


But I highly suggest you to not use any global variable. Because anyone can change its values and it will be harder for us to debug.

# The Lifetime of JavaScript Variables

- The lifetime of a JavaScript variable starts when it is declared.

- Function (local) variables are deleted when the function is completed.

- In a web browser, global variables are deleted when you close the browser window (or tab).

Comment if  I have committed any mistake.
Let's connect on my socials.
I am always open for new opportunities , if I am free :P

[Linkedin](https://linkedin.com/in/itsmesaurav/)| [Twitter](https://twitter.com/xauravww/) | [ShowwCase](https://showwcase.com/xauravww/)