Emmanuel Akinfulubi

JavaScriptEvents

Store a shopping cart in sessionStorage in JavaScript

Intermediate · 4 min read

A shopping cart has to remember what you put in it while you move from page to page. If it forgot every time the page reloaded, nobody could buy anything. For a cart that only needs to last while the tab is open, browsers offer sessionStorage. The catch is that it only stores text, and a cart is a list of objects.

In this tutorial you will keep a cart of bus tickets in sessionStorage, turn it into text and back with JSON, recover safely when the stored text is broken, and add up prices without rounding errors. You should know what arrays and objects are, and have used try and catch.

sessionStorage and localStorage

Both store pairs of keys and values for your site, with the same methods: setItem, getItem, removeItem and clear. The difference is how long they last:

  • sessionStorage belongs to one tab. It survives a reload, and is gone when the tab closes.
  • localStorage lasts until something clears it, across tabs and browser restarts.

They are separate stores, so the same key can hold different values in each. Both store strings only.

JSON in one paragraph

JSON is a way of writing data as text. JSON.stringify(value) turns arrays and objects into a string. JSON.parse(text) turns that string back into arrays and objects. It's how structured data fits into a store that only holds text.

Here is the exercise. Try it yourself first, or read on and we will build it together.

17 A cart held in sessionStorage

fair

Keep a shopping cart in sessionStorage. Since it holds only strings, the cart has to be serialised.

Stuck? Three hints, smallest first
  1. 1. JSON.stringify going in, JSON.parse coming out.
  2. 2. JSON.parse throws on malformed input, so it needs a try/catch.
  3. 3. sessionStorage lasts for the tab; localStorage lasts until it is cleared.

Step 1: why you can't store the object directly

Step 1

sessionStorage.setItem('cart', [{ name: 'Ticket to Abuja', qty: 1 }]);
console.log(sessionStorage.getItem('cart')); // [object Object]

Storage turns the value into a string the simplest way it can, and for an object that's the useless text [object Object]. The ticket's details are lost.

Step 2: stringify going in, parse coming out

Step 2

const cart = [{ name: 'Ticket to Abuja', kobo: 450000, qty: 1 }];
sessionStorage.setItem('cart', JSON.stringify(cart));
console.log(sessionStorage.getItem('cart')); // [{"name":"Ticket to Abuja","kobo":450000,"qty":1}]
const back = JSON.parse(sessionStorage.getItem('cart'));
console.log(back[0].name, back[0].qty); // Ticket to Abuja 1

The stored value is now readable JSON text, and parsing it gives back a real array of objects.

Step 3: read the cart safely

Stored data can go wrong in three ways. Each needs handling:

Step 3

const KEY = 'gsh-cart';
function readCart() {
  try {
    const value = JSON.parse(sessionStorage.getItem(KEY));
    return Array.isArray(value) ? value : [];
  } catch {
    return [];
  }
}
console.log(readCart()); // []: nothing stored, JSON.parse(null) is null
sessionStorage.setItem(KEY, '{not json');
console.log(readCart()); // []: JSON.parse threw, caught
sessionStorage.setItem(KEY, '"a string"');
console.log(readCart()); // []: valid JSON, but not a list

Taking them in turn:

  • Nothing stored. getItem gives null, and JSON.parse(null) gives null. Not an array, so we return an empty cart.
  • Broken text. JSON.parse('{not json') throws a SyntaxError. The catch turns that into an empty cart instead of a crash.
  • The wrong shape. '"a string"' is perfectly valid JSON for a string. It parses fine, so try alone wouldn't catch it. Array.isArray does.

Step 4: add to the cart

Step 4

const writeCart = (cart) => sessionStorage.setItem(KEY, JSON.stringify(cart));
function addToCart(name, kobo) {
  const cart = readCart();
  const existing = cart.find((item) => item.name === name);
  if (existing) existing.qty++;
  else cart.push({ name, kobo, qty: 1 });
  writeCart(cart);
  return cart;
}
sessionStorage.removeItem(KEY);
addToCart('Ticket to Abuja', 450000);
addToCart('Ticket to Kano', 620000);
addToCart('Ticket to Abuja', 450000);
console.log(readCart().map((i) => `${i.qty} x ${i.name}`)); // ['2 x Ticket to Abuja', '1 x Ticket to Kano']

Every change follows the same pattern: read, change, write back. Adding a ticket that's already there raises its quantity, instead of adding a second line for the same ticket.

Step 5: add up the money in kobo

Prices are stored in kobo, the smallest unit of the naira (100 kobo make 1 naira), as whole numbers. Here's why:

JavaScript

console.log(45.00 + 0.1 + 0.2); // 45.300000000000004
console.log(450000 + 620000);   // 1070000

Computers store decimals like 0.1 in binary, which can't hold them exactly, so tiny errors creep in. Whole numbers don't have that problem. Do the sums in kobo, and only turn the result into naira when you show it:

Step 5

const total = (cart) => cart.reduce((sum, item) => sum + item.kobo * item.qty, 0);
const naira = (kobo) => '\u20a6' + (kobo / 100).toLocaleString('en-NG', { minimumFractionDigits: 2 });
console.log(total(readCart()));        // 1520000
console.log(naira(total(readCart()))); // ₦15,200.00

reduce walks through the cart, adding price times quantity for each line. toLocaleString adds the comma and the two decimal places, and '\u20a6' is the naira sign.

The full solution

The full solution uses a small in-memory sessionStorage with the real methods. Its checks confirm the cart starts empty, items are added, the same item raises its quantity instead of adding a line, the total is right in kobo and formats as ₦15,200.00, the stored value is a string that survives a round trip, broken JSON, the wrong shape and JSON null all give an empty cart, and sessionStorage is separate from localStorage. Press Run, then try the live demo, reload its frame, and see the cart survive.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const KEY = 'gsh-cart';

// Reading has to survive: a missing key, malformed JSON, and valid JSON of the
// wrong shape. All three happen to data that lives in a browser.
function readCart() {
  try {
    const value = JSON.parse(sessionStorage.getItem(KEY));
    return Array.isArray(value) ? value : [];
  } catch {
    return [];                        // malformed: start over rather than crash
  }
}

const writeCart = (cart) => sessionStorage.setItem(KEY, JSON.stringify(cart));

function addToCart(name, kobo) {
  const cart = readCart();
  const existing = cart.find((item) => item.name === name);
  if (existing) existing.qty++;
  else cart.push({ name, kobo, qty: 1 });
  writeCart(cart);
  return cart;
}

// Money in kobo, as integers. 0.1 + 0.2 is not 0.3 in any binary float.
const total = (cart) => cart.reduce((sum, item) => sum + item.kobo * item.qty, 0);
const naira = (kobo) => '\u20a6' + (kobo / 100).toLocaleString('en-NG', { minimumFractionDigits: 2 });

console.log('empty to begin with       :', readCart());
addToCart('Ticket to Abuja', 450000);
addToCart('Ticket to Kano', 620000);
addToCart('Ticket to Abuja', 450000);        // same item again
const cart = readCart();
console.log('cart                      :', cart);
console.log('total                     :', naira(total(cart)));
console.log('stored as a string        :', sessionStorage.getItem(KEY).slice(0, 60) + '...');
console.log('its type                  :', typeof sessionStorage.getItem(KEY));

// Malformed JSON in the key.
sessionStorage.setItem(KEY, '{not json');
console.log('with malformed JSON stored:', readCart(), '<- recovered, did not throw');

// Valid JSON of the wrong shape.
sessionStorage.setItem(KEY, '"a string"');
console.log('with the wrong shape      :', readCart(), '<- also recovered');

Output


      
17 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test('the cart starts empty', (() => { sessionStorage.removeItem(KEY); return readCart(); })(), []);
test('adding an item stores it', (() => { addToCart('Ticket to Abuja', 450000); return readCart().length; })(), 1);
test('a second, different item is added', (() => { addToCart('Ticket to Kano', 620000); return readCart().length; })(), 2);
test('adding the same item again raises the quantity', (() => { addToCart('Ticket to Abuja', 450000); return readCart()[0].qty; })(), 2);
test('rather than adding a duplicate line', readCart().length, 2);
test('the total is computed in kobo', total(readCart()), 450000 * 2 + 620000);
test('and formatted as naira', naira(1520000), '\u20a615,200.00');
test('because 1,520,000 kobo is 15,200 naira', 1520000 / 100, 15200);
test('the stored value is a string', typeof sessionStorage.getItem(KEY), 'string');
test('which survives a round trip', JSON.parse(sessionStorage.getItem(KEY)).length, 2);
test('malformed JSON gives an empty cart, not a crash', (() => { sessionStorage.setItem(KEY, '{not json'); return readCart(); })(), []);
test('valid JSON of the wrong shape does too', (() => { sessionStorage.setItem(KEY, '"a string"'); return readCart(); })(), []);
test('and JSON null as well', (() => { sessionStorage.setItem(KEY, 'null'); return readCart(); })(), []);
test('sessionStorage is separate from localStorage', (() => { sessionStorage.setItem('shared', 'session'); localStorage.setItem('shared', 'local'); return [sessionStorage.getItem('shared'), localStorage.getItem('shared')]; })(), ['session', 'local']);
test('money kept in kobo avoids float error', 450000 + 620000, 1070000);
test('whereas the same sums in decimal naira drift', 45.00 + 0.1 + 0.2 === 45.3, false);
test('by a tiny but real amount', 45.00 + 0.1 + 0.2, 45.300000000000004);

Adapted: an in-memory sessionStorage with the real API. The assertion that sessionStorage and localStorage hold different values for the same key reflects the real difference — sessionStorage is scoped to the tab and goes when the tab closes, localStorage persists until something clears it.

Because storage is strings only, anything structured needs JSON.stringify and JSON.parse. The reading side is where the care goes, and all three failure modes are asserted: malformed JSON (JSON.parse throws), valid JSON of the wrong shape ("a string" parses fine and is not a cart), and the literal null. The Array.isArray check after parsing is what catches the second, which a try/catch alone would let straight through.

Prices are in kobo, as integers. Storing naira as a decimal invites the float error the last assertion demonstrates. Convert to a decimal only when formatting for display.

Common mistakes

  • Storing objects without JSON.stringify. You get [object Object] and the data is gone.
  • Trusting JSON.parse. It throws on broken text and happily returns the wrong shape. Use try and check with Array.isArray.
  • Storing money as decimal naira. Adding decimals drifts. Keep whole kobo and format only for display.

Try it yourself

  1. Add a removeFromCart(name) that lowers the quantity, and removes the line when it reaches 0.
  2. Show a badge with the total number of tickets, the sum of every qty.
  3. Switch the cart to localStorage, close the tab, and open the page again. What's different?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.