The today over lesson is about the How to Use Function Scope in JavaScript. I hope is useful for you.

var a = 4;
function foo(x){
 var b = a * 4;
fucntion bar(y){
var c = y * b;
return c;
}
return bar(b);
}
console.log(foo(a));

———————————————————————————————————————————————-

In JS there are two tyoes of scope:

  • Local Scope
  • Global Scope

Scope determines the accessibility(visibility) of these variables. Variables defined inside a function are not accessible (visible) from outsied the function

Now, lets understand Local & Global JS variables.

———————————————————————————————————————————————-

Local JAvaScript Variables

Varibles declared within a JavaScrip funcion, become LOCAL to the function. Ex:

// code here can NOT use stdName

fuction myFunction(){
    var stdName = "Priya";
    
    // Code her CAN use stdName
}

Function Scope: They can only be accessed from within the function.

DID YOU KNOW?

Local varibles are created when a function starts, and deleted when the fucntion is completed.

———————————————————————————————————————————————-

Global JavaScript Varibles

A variable declared outside a function, becomes GLOBAL.

var stdName = "Priya";

// code her can use stdName
function myFunction(){
   // code here can also use stdName
}

Global Scope: All scripts and functions on a web page can access it.

DID YOU NKOW?

In JavaScript, objects and functions are also varibles.

———————————————————————————————————————————————-

Automatically Global

  • If you assign a value to a varible that has not been declared, it will automatically become a GLOBAL varibles.
  • This code example will declare a global varible stdName, even if the value is assigned inside a function.
myFunction();
// code here can use stdName

function myFunction(){
   stdName = "Priya";
}

———————————————————————————————————————————————-

Tip:

Do NOT create global varibles unless you intend to.

Because,

  • You global varibles (or functions) can overwrite window varibles (or functions).
  • Any funcion, including the window object, can overwirte you global varibles and functions.

DID YOU KNOW?

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

———————————————————————————————————————————————-

So, did you learn sometthing new about function scope?

I hope this lesson be useful for you.

Source: https://www.instagram.com/webapp_creator/