The scope of activity is the use of variables. The scope of a variable is the region of your program in which you can access the variable, by using its name. The scope of a variable determines the visibility of that variable. Variables defined inside a function are not visible (or have no scope) from outside the function.

Scope Area

Functions and objects defined with JavaScript are declared as variables.

The scope of JavaScript is the use of variables, objects and functions.

Functions created with JavaScript have scope.

Local variables

Variables created inside the function are called local variables.

Local variables are accessed within the scope/function.

<script>
// fullName variable cannot be accessed from here
function functionName() {
    var fullName = "Baransel ARSLAN";
    // fullName variable can be accessed from here
}
</script>

Local variables are only declared inside the function.

Variables with the same name can be used in different functions.

<script>
functionName();
alert(typeof fullName); // undefined

function functionName() {
   var fullName = "Baransel ARSLAN";
   alert(fullName); // Baransel ARSLAN
}
</script>

Local variables are created when the function is called and cleared when the function terminates.

Global variables

Variables created outside the function are called global variables.

The scope of global variables is the web page.

Accessible from all code and functions on the web page.

<script>
   var fullName = "Baransel ARSLAN";
   // fullName variable can be accessed from here
   
   function functionName() {
       // fullName variable can be accessed from here
   }
</script>

If a value is assigned to a variable without creating a variable with JavaScript, the variable becomes a global variable thanks to hoisting.

<script>
functionName();
alert(fullName); // Baransel ARSLAN

function functionName() {
    fullName = "Baransel ARSLAN";
    alert(fullName); // Baransel ARSLAN
}
</script>

It is not recommended to assign a value without creating a variable.

JavaScript throws an error when using strict mode.

Global variable scope

The scope of JavaScript global variables is the entire HTML document.

JavaScript global variables are kept in the window object.

<script>
   var fullName = "Baransel ARSLAN";
   alert(window.fullName); // Baransel ARSLAN
</script>

Lifespan

The JavaScript variable’s lifetime begins when the variable is created.

Local variables expire and are deleted when the function completes its operation.

Global variables expire when the web page is closed.

However, if a new window is opened from the closed page, the lifetime of the variable ends with the closing of the opened windows.