Previous
Dialogs 
Next
Arrays 
ABC of JavaScript : An Interactive JavaScript Tutorial
Variables

Variables

JavaScript is a loose typing language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. You could use the 'var' keyword to define a variable. Using var outside a function is optional; you can declare a variable by simply assigning it a value. However, it is very recommended to use var, and it is necessary in functions if a global variable of the same name exists. The variables declared with the var keyword in a function will be in the local scope of the function(it will not exists outside the function). But if a variable is created without the var keyword, it will become a global variable.

var name="Binny"; //A String
site="http://www.bin-co.com/"; //Another String
number=13; // Number
precise_number = 12.9904289; //Float
var char = 'B'; //Character

Now the variable 'name' has a the value binny and the variable 'site' has the value 'http://www.bin-co.com'. We can use alert() display it.

alert("My name is "+name+" and my site is "+site);

This will display a message box with this message in it

My name is Binny and my site is http://www.bin-co.com/

Now try it out in our T-Box - just type the three blue lines given above into the below box and hit the 'Run' button to see your script in action.

And if you name is not Binny, change the name variable to whatever your name is. For example...
var name="Clark Kent";

Variables can store numbers the same way it can store stings. For example

var a=5;
var b=4;
var c=a+b;
alert("The sum of "+a+" and "+b+" is "+c);

Copy it to the T-Box if you want to see it in action. Here two Numbers are added and their result is stored in a third variable.

A word about the '+' operator - this is both a concatenation operator and a addition operator. Not a good idea, but that is what we have. If the variables on both side of the operator are numbers, it will return the sum of the numbers. If either variable is a string, the operator will return the concatenated string.

Previous
Dialogs 
Next
Arrays 
blog comments powered by Disqus