Google News
logo
Javascript Variables
JavaScript uses reserved keyword var to declare a variable. A variable must have a unique name. You can assign a value to a variable using equal to (=) operator when you declare it or before using it.

There are two types of variables in JavaScript: 
1. local variables  : A variable that is declared inside of a function definition is called local variable and has scope to that function only. 
2.global variables :  A variable that is declared outside of a function definition is called a global variable and its scope is throughout your program means its value is accessible and modifiable throughout your program.
Basic Syntax :
var <variable-name>;

var <variable-name> = <value>;
Local Variable Example :
<html>
<head>
<title>Local Variable</title>
</head>
<body>
 
<p>The local variable website cannot be accessed from code outside the function:</p>
 
<p id="web"></p>
 
<script type="text/javascript">

  myFunction();
  document.getElementById("web").innerHTML =
  "This is sample webste " + typeof url;
 
  function myFunction() {
    var url = "www.freetimelearning.com";
  }

</script>
 
</body>
</html>
Output :

The local variable website cannot be accessed from code outside the function:

This is sample webste undefined

Global Variables Example :
<html>
<head>
<title>Global Variable</title>
</head>
<body>

<p>A Global variable can be accessed from any script or function.</p>
 
<p id="web"></p>
 
<script>

  var url = "www.freetimelearning.com";
  myFunction();
 
  function myFunction() {
    document.getElementById("web").innerHTML =
    "This is sample website " + url;
  }

</script>
 
</body>
</html>
Output :

A Global variable can be accessed from any script or function.

This is sample website www.freetimelearning.com