JavaScript Variables

You are currently viewing JavaScript Variables

JavaScript Variables

A variable is a container or a symbolic name used to store data or values. Variables allow us to store and manipulate information in our code. They have a name (identifier) and a value associated with them, which can be changed as the program runs.

JavaScript uses reserved keyword “var” to declare variables. A Variable must have a unique name.

There are some rules while declaring a JavaScript variable.

  • Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  • After first letter we can use digits (0 to 9), for example value1.
  • JavaScript variables are case sensitive, for example ‘age’ and ‘AGE’ are different variables.

Syntax for declaring JavaScript Variable:-
var <variable-name>=<value>

Example :-
var x=41; // variable store numeric value
var name= “Vishal Uttam” ; //variable store string value

JavaScript program to illustrate the variables :-

				
					
<html>
<body data-rsssl=1>
<script>  
var a = 10;  
var b = 20;  
var sum=a+b;  
document.write("The sum of a+b = " +sum);  
</script>  
</body>
</html>

				
			
				
					Output-:
The sum of a+b =30

				
			

There are two types of variables in JavaScript : local variable and global variable.


1. JavaScript local variable-: A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:

				
					<script>  
function myFun(){  
var x=10;   //local variable  
alert(x); //alerts 10
}  
</script>

				
			

2. 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. For example:

				
					<script>  
var x=10;   //global variable  
function myFun(){  
alert(x); //alerts 10
}  
</script>

				
			

Leave a Reply