JS Variable Types

Two Types of JavaScript Variables
There are two types of Variables in JavaScript :

  1. Local Variables
  2. Global Variables

Local Variable :

  1. Variable declared inside JavaScript Function will become “local Variable“.
  2. Local variable is visible inside the function in which it is declared.
  3. Other Function cannot access local variable declared in another function.
  4. Local Variables are destroyed after execution of function.
<script type="text/javascript">
function message()
var name="Pritesh";

<input type="button" value="Click me!" onclick="message()" />


Global Variable :

  1. Variable declared outside JavaScript Function will become “Global Variable“.
  2. All Scripts and JavaScript Functions can access Global Variables.
  3. When User closes browser global variable is destroyed.
  4. Variables declared without using “var keyword” will be considered as Global Variable.

<script type="text/javascript">
var name;

<script type="text/javascript">

<p>Global Variable Can be accessed
 from other Script</p>


Difference between Global Variable and Local Variable

Parameter Global Variable Local Variable
Scope All JavaScript Functions and Scripts Function in which it is declared
Destroyed When User Closes browser After Execution of function
Can we declare same variable again Not possible Possible but outside function in which it is declared