What is the lifetime of JavaScript variables?

JavascriptWeb DevelopmentFront End Technology

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 −


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

Live Demo

   <body onload = checkscope();>
         var myVar = "global";   // Declare a global variable
         function checkscope( ) {
            var myVar = "local"; // Declare a local variable
Published on 23-Jan-2018 17:38:17