Cookie Concepts

Last month, we had an in-depth look at the JavaScript variable. We dwelled on one of its weaknesses: that it is automatically destroyed by the browser when the Web page that it belongs to is no longer displayed. We then looked at a way of getting around this weakness by stashing the variable in another document (in the example we considered, a frameset) that would remain loaded by the browser for as long as we needed the variable.

If you didn’t read that article and you’re thinking that that sounds like a lot of trouble to go to, you’re right. If you did read last month’s article, you know it was a lot of trouble! The reason it was so much trouble to do is that JavaScript variables weren’t designed with persistence in mind. Cookies were.

You can think of cookies as JavaScript variables that have all the persistence stuff built right in. Just like variables, cookies have names and you assign them values. Unlike variables, cookies are not destroyed by the browser when the page they belong to is unloaded. Instead, the browser hangs on to cookies until they are needed again.

With all the added power they have to offer, you might wonder why we don’t all just use cookies instead of variables. There can be a couple of answers to this question. First, some people disable cookies in their browsers. As we’ll see, cookies are quite safe and, when used properly, do not in any way violate the privacy of visitors to your site. When they were first introduced, however, cookies got a bad rap. As a result, some users choose to disable them just because someone they know said that cookies were bad. For this reason, relying on cookies for the basic functions of your site can sometimes be a risky proposition.

The main reason for not using cookies as a drop-in replacement for variables, however, is convenience. Variables are extremely convenient. It takes one line of code to set a variable, and making use of the value stored in a variable usually just involves putting the name of the variable where you’d like the value to appear. Cookies are a good deal more complex, and have a few limitations that would get in the way. That’s all I’ll say on this for now, as the rest should become clear by the end of this article.

Don’t let my talk of complexity and limitations scare you away, though. When it comes to sharing data between two or more Web pages, cookies are just what you need! In the next section we’ll go over the basics: creating a cookie, setting its value, reading the value back again, and changing the stored value. Finally, we’ll develop a simple example of a cookie in action, the complete code for which will be provided.

Comments are closed.