Beware of duplicate cookie values

Came across a strange problem today that I thought I should record since I’ve already wasted enough time investigating it. The problem was that a web site was recording a setting to a cookie each time a page was unloaded; e.g. Preference1. Any page can then read the cookie and take appropriate actions. However, for some reason the preference was not correctly read on any other page. Puzzled I examined the document.cookie property. For some strange reason the value was duplicated; e.g. Preference1=hello; Preference2=bla; Preference1=goodbye. So when the page wrote to the cookie the 2nd version changed but when the cookie was read the 1st version was taken. Once I cleared the cookies for the domain everything went back to normal. The site only has one domain, no sub-domain or anything. Very strange behaviour.

So there it is, an aide memoir for me, but if anyone can provide an explanation I would be grateful. I should mention this was all client side JavaScript.