The Sysadmin Notebook  

Sitemap

Javascript Variables

Javascript Datatypes and Variable Declaration

Contents

Javascript is untyped: a variable can be used to hold any of the various datatypes supported by javascript. Javascript will automatically convert variables from one type to another as required. Local variables (variables defined within a function) should be declared with the 'var' keyword, otherwise the variable is implicitly declared with global scope. Local variables are defined throughout the function - even before they have been declared. Local variables will hide global variables whilst in scope. Function parameters are also local variables.

Typically, primitive datatypes (numbers, boolean values, null and undefined) have a fixed size in memory and can be considered as containers for their assigned value. Primitive datatypes are thus manipulated by value. Reference types (objects, arrays, functions) are pointers to their data and therefore are manipulated by reference. If you copy a primitive datatype, changes to the copy do not affect the original. If you copy a reference, the reference points to the original data, and changes to the copy will affect the data referred to by both the original and the copy.

Numbers

Top Bottom

Numbers can be expressed as base-10 or hexadecimal (using a '0x' prefix). Apart from the basic mathematical operators, more complex functions are available from the Math object:

var myNumb = 45;
var myCos = Math.cos(myNumb);
alert("Cosine of " + myNumb + " = " + myCos);

The isNaN() function returns true if a variable contains data that can be treated as numeric. Data that is either too large or too small to be stored in a numeric variable will be equal to 'Infinity' or '-Infinity': use isFinite() function to test for strings that can be represented within the bounds of the valid ranges for javascript numeric datatypes. Data that passes the isNaN test, can be converted to a number by subtracting '0': myVar -= 0;

if (typeof(myVar) != 'number') {
    alert ("Not a number " + myVar);
    if (isFinite(myVar)) {
        myVar -= 0;
        alert("After subtract 0 myVar is now a " + typeof(myVar));
    }
    else if (isNaN(myVar)) {
        alert("myVar cannot be implicity converted to a number");
    }
    else if (myVar == Infinity || myVar == -Infinity) {
	alert ("myVar is numeric, but too large to represent as a numeric datatype");
    }
}
else {
    alert(typeof(myVar));
}

Strings can also be converted to numbers using the Number() constructor as a function, or using the parseInt() and parseFloat() functions.

var myString = "Hello World";
var myNumb1 = Number(myString);
alert("myNumb1 Type: " + typeof(myNumb1) + ". Value: " + myNumb1);
var myNumb2 = parseInt(myString);
alert("myNumb2 Type: " + typeof(myNumb2) + ". Value: " + myNumb2);

Strings

Top Bottom

Strings are a primitive data type, but a corresponding String class provides several methods and functions that can be used transparently with string data.

To convert a number to a string, concatenate the number with an empty string:

var myInt = 45;
alert typeof(myInt);
myInt += '';
alert typeof(myInt);

Numbers can also be converted to strings using the String() constructor as a function, or using the toString() method of the number object.

var myInt = 45;
var myStr1 = String(myInt);
alert("myStr1 Type: " + typeof(myStr1) + ". Value: " + myStr1);
var myStr2 = myInt.toString();
alert("myStr2 Type: " + typeof(myStr2) + ". Value: " + myStr2);

Booleans

Top Bottom

Boolean datatypes are either 'true' or 'false', and are the result of comparisons, normally used in control structures:

var myBool1 = 'true';
alert ("myBool1 Type: " + typeof(myBool1) + ". Value " + myBool1);
var myBool2 = (myBool1 == 'true');
alert ("myBool2 Type: " + typeof(myBool2) + ". Value " + myBool2);

Functions

Top Bottom

Functions can be defined using the 'function' keyword, followed by the function name, brackets to hold parameters and curly brackets to hold the function logic. The function can then be called by name:

function prntValue(x) {
    alert ("Variable Type: " + typeof(x) + ". Value " + x);
}
prntValue('true');

The same function can be defined using the 'function literal' notation:

var prntValue = function(x) {alert ("Variable Type: " + typeof(x) + ". Value: " + x);}
prntValue('true');

Functions can also be defined using the Function() constructor, but this is neither very efficient nor very intelligible:

var prntValue = Function("x", 
'alert ("Variable Type: " + typeof(x) + ". Value: " + x);');
prntValue('true');

Objects

Top Bottom

A more detailed discussion of objects can be found here

Objects are collections of named values. The named values are called properties. Properties can be arrays, functions, other objects or any other data type. Function values of objects are called methods.

Objects used as associative arrays reveal their properties using square bracket notation:

image["width"]

Objects are created using constructor functions:

var myObj = new Object();
var now = new Date();
var pattern = new RegExp("javascript", "i");

Set properties for objects using 'dot' notation:

var myObj = new Object();
myObj.height = 34;
myObj.width = 45;

Objects can be instantiated using 'object literal' notation:

var myObject = { height:34, width:45 };

Object literals can be nested.

Arrays

Top Bottom

Arrays are a special type of object represeting a collection of numbered data values. Arrays can be created using the Array() constructor:

//Array Constructor
var myPC = new Array();
myPC[0] = "Packard Bell";
myPC[1] = 414325;
myPC[2] = true;
myPC[3] = { OS:Fedora, Version:7};
//Array Constructor plus initialisation
var myNextPC = new Array(
"Hewlett Packard", 43543, false, {OS:SuSE, Version:11.2});
//Array literal notation
var myOtherPC = ["Hitachi", 43342, true, {OS:Gentoo, Version:5}];
//Creates array with 7 undefined elements:
var weekDays = new Array(7);

The array constructor notation can be nested and include undefined values