Javascript Variable

A variable is a name or symbol that contains a value. The var keyword is used to declare javascript variable.


var text1 = 'Hello world';
var text2 = 'Hello India';        

Unlike C, C++, javascript does not define datatype while declaring a variable. So javascript variable can hold any type of values. You can also assign a value to a variable without using var keyword, like -

text1 = 'Hello World'; 

The above variable declaration is also supported, but this is not recommended and not a good practice to declare a variable like this.

Scope of a variable -

The scope of a variable is the region in which it can be called. There are two types of variable scope.

1. Local Variable

When a variable is declared within a function, then it is accessed within that function block only and is called local variable. We cannot access it outside of the function.

2. Global Variable

It has global scope and can be defined and called anywhere in the script. But to use this within a function, you will have to pass this as a parameter.

var a1 = 10;   
function add(a1) {


Variable Definition Rules

1. A variable name can start with a letter, number, underscore or dollar sign.


var a = 'txt323';
var b = '_txt';
var c = $txt;
var d = '22txt';     

All the above are valid variable definition.

2. Variable name cannot be a reserved keyword.

3. You can declare one or more than one variable at a time.

var a1, a2, a3, a4; 

4. Variables are case sensitive.

var a1 = 10;
var A1 = 10;    

Both are different variables.

Read more articles

General Knowledge

Learn Popular Language