JavaScript Variables

Variables are used to store data values. Use "var" keyword befor the variable name Example: var x;  to declare javascript variables. (=) is called equal sign that is used to assign values to variables.

Example:

var a = 10; // a is variable name
Variables are containers for storing data values.

There are two types of variables in JavaScript :

  1. local variable and 
  2. global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers):
  • Variable name must start with a letter like (a to z or A to Z), underscore( _ ), or dollar( $ ) sign. 
  • After first letter we can use digits (0 to 9), Example variable2. 
  • JS variables are case sensitive, Example a and A are different variables.
Correct JavaScript variables:
var a = 100; 
var _variable="Bangla";
Incorrect JavaScript variables:
var  521=10; 
var *ba=450;
Let’s see a simple example of JavaScript variable:
<html> 
<body> 
<h2>JavaScript Variables Example</h2> 
</body> 
</html>
<script> 
var a = 50; 
var b = 5; 
var c = a + b; 
document.write(c); 
</script>

Result:
JavaScript Variables Example
55
JavaScript local variable:
Local variable is declared inside block or function in javascrupt. Local variable is accessible within the function or block only. 

Example:

<script>
 function xyz(){
  var a = 100; // JavaScript local variable
 }
</script>

or

<script> 
 If(a<b){ 
  var a = 15; // JavaScript local variable 
 } 
</script>
JavaScript global variable:
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable.
Example:
<html> 
<body> 
<script> 
var global_variable= 100; //global variable 
function abc(){ 
document.writeln(global_variable); 
function xyz(){ 
document.writeln(global_variable); 
abc(); //call JavaScript function 
xyz(); 
</script> 
</body> 
</html>
Project Source Code:
<!DOCTYPE html> 
<html> 
<body> 
<h2>JavaScript Variables</h2> 
<h4>variables are used to store data values.</h4> <h4>JavaScript always use the <b style="color: red; font-weight: bold">var</b> example: var x; keyword to declare javascript variables.</h4> 
<h4>An <b style="color: red; font-weight: bold">equal sign (=)</b> is used to assign values to variables. </h4> 
<p>Here x is a variable. Then assigned the value to variable x</p> 
<p id="example"></p> 
</body> 
</html> 
<script type="text/javascript"> 
var x = 10 + 12; // here = is used to assign the value of variable x and used var keyword to declare the variable document.getElementById("example").innerHTML = "The value of Variable x is ="+x; 
</script>


EmoticonEmoticon