How can I delete a cookie using JavaScript?

I have a function for creating a cookie, and I want to know if it’s correct. Additionally, how can I delete the cookie at the beginning of my program? I’m looking for a simple way to javascript delete cookie.

Here’s my code for creating the cookie:

function setCookie(c_name, value, days) {
  document.cookie = c_name + "=" + escape(value);
}

setCookie('cookie_name', mac);

And for deleting the cookie, I tried:

function eraseCookie(c_name) {
  createCookie(c_name, "", -1);
}

Is this the right approach, or is there a more efficient way to delete cookies in JavaScript?

Been in web development for over a decade, and honestly, the classic trick still works best for me. If you want to javascript delete cookie, the most reliable way is to set it with an expired date. Here’s a simple method I always recommend:

function deleteCookie(name) {
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

You’re on the right track if you’re doing something like this. Just make sure the path matches how the cookie was initially set — otherwise, you might think you deleted it, but it’ll still linger. For javascript delete cookie across your whole site, this is really the go-to move.

Been working with multi-domain web apps for years — small tip: watch the path and domain." Building on @ishrth_fathima’s point, sometimes a javascript delete cookie doesn’t work because the domain and path aren’t exactly matched. Even if you set the expiry correctly, mismatch here means the cookie survives. Here’s a version I use when my app spans folders or subdomains:

function deleteCookieExact(name) {
  document.cookie = name + "=; path=/; domain=" + window.location.hostname + "; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
}

Manually specifying the domain can really save you headaches. For javascript delete cookie to actually succeed, matching exactly how the cookie was originally set is critical.

Having handled tons of frontend projects, I realized keeping cookie handling consistent saves a lot of trouble later.

Adding to @tim-khorev’s advice — it gets even cleaner if you wrap it all in helper functions. If you’re using a createCookie() function (which you hinted at), you can also design a neat pair for setting and deleting cookies. Here’s how I handle javascript delete cookie consistently:

function eraseCookie(name) {
  setCookie(name, "", -1);
}

function setCookie(name, value, days) {
  var date = new Date();
  date.setTime(date.getTime() + (days*24*60*60*1000));
  document.cookie = name + "=" + escape(value) + "; expires=" + date.toUTCString() + "; path=/";
}

This way, your set and delete operations behave predictably — less bug hunting later. Plus, managing javascript delete cookie with utilities like this scales better as your project grows.