Javascript Variables

Writing by shivdev on Thursday, 25 of October , 2007 at 4:46 pm

Remember, Javascript is not a strongly typed language. While using variables in Javascript, don’t bother about the type of data a variable is storing, instead what the variable is storing. These variables can store anything – even functions!! Here are some examples on using variables in Javascript.

var thisIsAString = 'This is a string';
var alsoAString = '25';
var isANumber = 25;
var isEqual = (alsoAString==isANumber);  // This is true, they are both 25.
var isEqual = (alsoAString===isANumber); // False one is a number,
                                         // the other a string.

var concat=alsoAString + isANumber;      // concat is now 2525
var addition=isANumber + isANumber;      // addition is now 50
var alsoANumber=3.05;     // is equal to 3.05 (usually).
var floatError=0.06+0.01; // is equal to 0.06999999999999999
var anExponent=1.23e+3;   // is equal to 1230

var hexadecimal = 0xff;   // is equal to 255.
var octal = 0377;         // is equal to 255.

var isTrue = true;   // This is a boolean, it can be true or false.
var isFalse= false;  // This is a boolean, it can be true or false

var isArray = [0, 'one', 2, 3, '4', 5]; // This is an array.
var four = isArray[4]; // assign a single array element to a variable.
                       // in this case four = '4'

var isObject = { 'color': 'blue',  // This is a Javascript object
                 'dog': 'bark',
                 'array': [0,1,2,3,4,5],
                 'myfunc': function () { alert('do something!'); }
               }

var dog = isObject.dog;  // dog now stores the string 'bark';
isObject.myfunc();       // creates an alert box with the value "do something!"
var someFunction = function() {
                      return "I am a function!";
}
var alsoAFunction = someFunction; //No () so alsoAFunction becomes a function
var result = alsoAFunction(); // alsoAFunction is executed here because ()
                              // executes the function so result stores the
                              // return value of the function which is
                              // "I am a function!"

Leave a comment

Category: Javascript

Shivdev Kalambi's Blog

Shivdev Kalambi is a Principal Software Engineer working at ArcSight. He has over 11 years' experience in software development and has worked with several technologies and played different roles and contributed to all phases of projects. Other non-tech activies include Ping-pong, Racquetball, Rock Climbing at PG and Swimming.