What is the lifetime of JavaScript variables?


The lifetime of a JavaScript variable begins when it is declared −

var rank;

A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.The completion of a function deletes the local variable.

A global variable has a global scope which means it can be defined anywhere in your JavaScript code. Global variables delete when the web browser is closed. However if a new page is loaded in the same browser window, then it remains.

Here’s the usage of global variables −

Example

You can try to run the following code to learn how to work with a scope of variables in JavaScript

Live Demo

<html>
   <body onload = checkscope();>
      <script>
         <!--
         var myVar = "global";   // Declare a global variable
         function checkscope( ) {
            var myVar = "local"; // Declare a local variable
            document.write(myVar);
         }
         //-->
      </script>
   </body>
</html>

Updated on: 15-Jun-2020

732 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements