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.
<html>
<head>
<script type="text/javascript">
function message()
{
var name="Pritesh";
alert(name);
}
</script>
</head>

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

</body>
</html>

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.
<html>
<body>

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

<script type="text/javascript">
document.write(name);
</script>


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

</body>
</html>

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