Our site is ads supported. Please disable your ad blocker and reload the page. Thank you!

JavaScript Variables Scope

1 1 1 1 1 JavaScript Variables Scope5.00Rating 5.00 (1 Vote)

In JavaScript there are two types of variables scope:

  • Local scope
  • Global scope

Scope determines the accessibility (visibility) of these variables.

Global variables can be accessed from any function.

The example of variable created in global scope:

 var userName = "Alice";

// code can use userName 
function myFunction1() {
    // code here can also use userName 
}
function myFunction2() {
    // code here can also use userName 
    function myFunction3() {
        // code here can also use the same userName 
    }
}

 

Local variables can only be accessed from the function they are declared.

 

// code here can NOT see userName 
function myFunction() {
    var userName = "Bob";
    // code here CAN see and use userName 
}

 

Monday the 19th.