Two Types of Variables in JavaScript

January 29, 2025 No Comments » Hits : 413






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

ParameterGlobal VariableLocal Variable
ScopeAll JavaScript Functions and ScriptsFunction in which it is declared
Destroyed WhenUser Closes browserAfter Execution of function
Can we declare same variable againNot possiblePossible but outside function in which it is declared

Incoming search terms: