I’m confused about what exactly goes into the ‘value’ part when creating cookies in JavaScript. Should this value be a reference to an existing variable in my code, or can it be any arbitrary string I want to store?
I’m working on implementing cookies in my current project but running into issues. Here’s my current code setup:
function setCookie(username, data, expireDays) {
if (expireDays) {
var expireDate = new Date();
expireDate.setTime(expireDate.getTime() + (expireDays * 24 * 60 * 60 * 1000));
var expiration = "; expires=" + expireDate.toUTCString();
} else {
var expiration = "";
}
document.cookie = username + "=" + data + expiration + "; path=/";
}
function getCookie(username) {
var cookieName = username + "=";
var cookieArray = document.cookie.split(';');
for (var j = 0; j < cookieArray.length; j++) {
var cookieItem = cookieArray[j];
while (cookieItem.charAt(0) == ' ') {
cookieItem = cookieItem.substring(1, cookieItem.length);
}
if (cookieItem.indexOf(cookieName) == 0) {
return cookieItem.substring(cookieName.length, cookieItem.length);
}
}
return null;
}
function deleteCookie(cookieName) {
setCookie(cookieName, "", -1);
}
Could someone explain what the data parameter should contain and provide a practical example of how to use these functions properly?
Cookies just store strings - whatever text you throw at the data parameter gets saved. It’s like writing to a text file that sticks around after refreshes and browser restarts. I’ve done setCookie(‘lastVisited’, new Date().toString(), 365) for visit tracking, or setCookie(‘shoppingCart’, ‘3’, 1) for item counts. You’re passing the actual value, not a reference. Here’s the catch I learned the hard way: everything becomes a string. Store the number 42? You’ll get back ‘42’ as text. Your functions cover the basics nicely, but I’d trim whitespace when retrieving values - browsers sometimes pad cookie data.
The data parameter can be any string value you want to store - it’s not tied to a variable name. It’s just the actual content you want saved between browser sessions. For example, if you’re storing user preferences, you’d call setCookie('userTheme', 'dark', 30) where ‘dark’ is the literal value. If you need to store objects or arrays, use JSON.stringify(myObject) when setting and JSON.parse() when retrieving. Your code looks good, but I recommend adding some error handling for edge cases. Also, keep in mind that cookies have size limits and may not handle special characters well. Use encodeURIComponent() when setting and decodeURIComponent() when reading to avoid issues with spaces or weird characters.
the data param can be any string you wanna save - it doesn’t have to be a var. for example, you could use setCookie(‘username’, ‘john123’, 7) to save ‘john123’ for a week. just keep in mind that cookies are strings, so even numbers will be converted to text.