// Check for cookie information
// Analysis
if( (visitString = getCookie("visits")) == null)
	{
	setCookie("visits", "1");
	visitString="1";
	}
else
	{
	numVisits = parseInt(visitString);
	numVisits++;
	visitString = "";
	visitString += numVisits;
	setCookie("visits", visitString);
	}

The first line of this code does something tricky, so examine it closely. The code first makes a call to the getCookie function, searching for the value of the 'visits' cookie, and the results are assigned to visitString. However, the assignment is statement is contained within an if statement. Once the value is assigned to the visitString variable, the value returned from the getCookie function will be compared to null.

The first code block following the if statement assumes that null was returned, signalling to the code that the cookie was not found. In this case, this is the first visit the the visitor has made to the page (in the last year, anyway). In this case, the visitString variable is assigned the value '1', and the setCookie funtion is called to create a new cookie.

The second block of code, following the else statement, is executed when the getCookie function returns a value. In this case, the cookie contains a string representation of an integer. Because we can't directly operate on strings as if they were integers, we have to first convert the value to an Integer using the parseInt() method. The parseInt() method takes a string value, and converts it to an integer value.

Once the conversion has been made, the number of visits is incremented, and a string representation of the number is assigned to the visitString variable. Because we first assign the visitString variable an empty string value, the variable is initialised to hold string values. Therefore, we we use the (+) operator, we are using the concatenation operator to add the string value of the numVisits variable. Because of JavaScript's type rules, an integer is always transformed to a string and concatenated with the + operator.

Finally, the code sets the visits cookie to an updated value reflecting the current visit.

Close Window