Notes on "Creating a client-side shopping cart" for Smashing Magazine

Notes on "Creating a client-side shopping cart" for Smashing Magazine

Some annotations on my recent article for Smashing Magazine.

In this post I'd like to address some of the most interesting issues related to my recent article on creating a client-side shopping cart on Smashing Magazine.

Why not just use cookies?

Evan Byrne says:

Why not just use cookies? There don't appear to be any significant advantages to using this instead. The only thing I can think of is the increased storage space.

Cookies aren't difficult to work with: http://www.quirksmode.org/js/cookies.html. There are also plenty of small libraries that make working with them even easier.

That's a really good point. Cookies are implemented in browsers practically since the beginning of the WWW and they are easy to handle. To set a cookie in JavaScript you have simply to write:


document.cookie = "test=Hello";

Now we have a cookie: its name is test and its value is Hello. To get the value of the cookie just set earlier:


var myCookie = document.cookie.replace( /(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1" );
console.log( myCookie ); // Hello

We can also create a jQuery utility object (a global jQuery object) to work with cookies:

So why not just use cookies? Simply put, using cookies makes sense when you have to support obsolete browsers that don't implement the most recent JavaScript APIs. Using native APIs is much better than implementing everything from scratch because the newly introduced HTML5 APIs provide a consistent and efficient way to manage web storage. In my opinion, cookies should be used only as a fallback mechanism.

Emptying the session storage safely

Andrea Giammarchi noticed that:

And he adds:

So we should take advantage of prefixes to make sure that we're not emptying the whole session storage but only removing our own items (i.e. the items set only by our code).