Arrays and cookies in javascript

So I was just working on a web project involving cookies. The site had a couple categories of pages that each had their own ‘tips’ for the user. The ‘tips’ can be hidden or shown by clicking on a button. So I figured rather than creating a page specific function to tell whether to keep the tip open or closed I would write one for all the pages. It started out rather easy, making the array, setting the cookie, reading the cookie, took less than an half an hour (I had previously created a set,get,and delete cookie functions in javascipt).

The Problem

I went to test it out and it worked on the first test. I saw ,,,0, meaning the first 3 pages had not been visited and the 4th had the ‘tips’ window closed. I was pumped, ready to move onto another task. I went to test another page and when I clicked the button guess what happened? Yeah I figured you would know what, but in case you didn’t, the array/cookie now looked like this ,,,,0,,,

I puttered around for an hour or so trying various things, I kept focusing on where I pulled the info from the cookie and set it to the new array.

showCookie= getCookie('showCookie');
showArray = new Array();
if(showCookie!= ''){
	for(i=0;i<=3;i++){
		showArray[i] = showCookie[i];
	}
}

It looked right to me. So I spent the next half hour digging around looking for what else it could have been. I looked at where I set the array, the length of the array before and after setting it. It always came out as what it was supposed to.

The Conclusion

Then it hit me. What if the array was no longer an array? What if when you set an array as a cookie value it becomes a string? Maybe the explanation for the cookie having these extra commas was that in fact when I was looping through the cookie ‘array’ I was actually appending a string of 4 commas into my new array. I tested this theory out by revising my code.

showCookie = getCookie('showCookie');

//When pulling the cookie array back in, it is a string not an array.
showCookieSplit = showCookie.split(",");

showArray = new Array();

if(showCookie!= ''){
	for(i=0;i<=3;i++){
		showArray[i] = showCookieSplit[i];
	}
}

It worked! Long story short, now I know that I should test everything, even the things I think to be true.

3 thoughts on “Arrays and cookies in javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>