Variables

Variables are basically containers that store our values and can be called anywhere in the apge depending upon the scope the variable. We will explain about the scope of variables later on this page. JavaScript is a 'loosely-typed' scripting language.

The syntax of JavaScript is similar to that of C or Java, but simpler and not as rich. Primitive data types include integers, reals, strings, and a associative arrays. Javascript is loosely typed, any variable can contain data of any type, and conversion is mostly automatic. However, it is case sensitive.

A variable name can begin with a letter or underscore. Since, javacsript is a case-sensitive language, variables are also case sensitive. Like other programing languages, variables are declared directly .


var alpha;
var name;
var alpha=1;
var name='Dolly';

Since, Javascript is a loosely typed language, the same variable be can be assigned different data type as shown without any error.


var myVariable = 1;  // integer
myVariable = 'Dolly'; // string
myVariable = '1.092'; // float
myVariable = false; // boolean 

Clearly , as shown above, the same variable can be used to store any variable - type.

Scope of variables

Scope decides upto what point a variable can be used. Once the code reaches out of scope , all other variables are destroyed. Here is an example showing scope of differnet variables.


if (cond1 is true){
if (sub_cond1 is true) {
   var myVar = 1;
   }
   else {
   var myVar = 2;
   }
   document.write(myVar); // will print the value of myVar
 }
 else {
 // do some other stuff 
 }
 document.write(myVar); // will not print anything
// since it is external to the braces in which it was defined

Thus, we can judge the scope of a variable by simply checking the braces. They are available only inside the braces in which they are defined.

Global Variables

To make a variable global, we need to define it such that it is external to none of the braces. This can be done if it is defined outside the function so that it can be assessed by any other function. An alternative way to make a function global is to define it without var keyword. It makes it global irrespective of the place it is defined.


alpha = 1;
myText = 'Hello World !!!';
// these are Global variables 

Comments

Comments are important part of any programming language. They make the code more interpretable for other users. In javascript, we use a // to make a single line comment and /* and */ to make a multiple line comment


// here goes my single line comment

/*
Its a multiple line comment.
We can write as many lines as we wish
*/

Member Login

Member Login




Not a Member? Sign Up!




Login to comment

Be the first to comment on this topic







  


<<< Wanna review

Continue >>>