Variable Declaration

Advertisements

Prev Tutorial Next Tutorial

Variable Declaration

Java script did not provide any data types for declaring variables and a variable in java script can store any type of value. Hence java script is loosely typed language. We can use a variable directly without declaring it.

Only var keyword are use before variable name to declare any variable.

Syntax

var x;

Rules to declaring a 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 x and X are different variables.

Variable declaration

Example

var x = 10;  // Valid
var _value="porter";  // Valid
var  123=20;  // Invalid
var #a=220;  // Invalid
var *b=220;  // Invalid

Example of Variable declaration in JavaScript

Example

<script>
var a=10;
var b=20;
var c=a+b;
document.write(c);
</script>

Output

30

Types of Variable in JavaScript

  • Local Variable
  • Global Variable

Local Variable

A variable which is declared inside block or function is called local variable. It is accessible within the function or block only. For example:

Example

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

or

Example

<script>  
If(10<13)
{  
var y=20;//javascript local variable  
}  
</script>  

Global Variable

A 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:

Syntax

<script>  
var value=10;//global variable  
function a()
{  
alert(value);  
}  
function b()
{  
alert(value);  
}  
</script>  

Declaring global variable through window object

The best way to declare global variable in javascript is through the window object. For example:

Syntax

window.value=20; 

Now it can be declared inside any function and can be accessed from any function. For example:

Example

function m()
{  
window.value=200; //declaring global variable by window object  
}  
function n()
{  
alert(window.value); //accessing global variable from other function  
}  

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements