Please help Ukrainian armed forces! Official Fundraising

JavaScript Variables Scope

1 1 1 1 1 JavaScript Variables Scope5.00Rating 4.50 (2 Votes)

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 
}

 

Saturday the 20th.