JavaScript Check If Cookie Exists with Examples

Cookies play an important role in web development by storing user information and preferences.

Either you are a proficient developer or a beginner, understanding how to check if a cookie exists using JavaScript is an essential skill.

In this article, we will discuss the different techniques and methods to help you perform this task smoothly.

Let’s begin and explore the world of JavaScript cookies!

When working with cookies in JavaScript, it’s important to be able to define whether a specific cookie exists or not.

This ensures that you can provide personalized experiences to users based on their stored preferences.

Here are some tried-and-true methods for checking the existence of a cookie:

Also read: JavaScript Decimal to Hexadecimal

One of the common methods to check if a cookie exists is by using the document.cookie property.

This property consists of all the cookies associated with the current document. You can use JavaScript to search for the appropriate cookie within this string.

For example:

function checkCookie(cookieName) {
    var cookiesFunction = document.cookie.split(';');
    for (var i = 0; i < cookiesFunction.length; i++) {
        var cookie = cookiesFunction[i].trim();
        if (cookie.indexOf(cookieName + '=') === 0) {
            return true;
        }
    }
    return false;
}

Method 2: Utilizing Cookies.get()

If you are using a library like js-cookie, the process becomes even simpler.

This library provides an advantageous method called Cookies.get() which allows you to restore the value of a cookie by its name.

If the cookie does not exist, the method will return undefined.

Here’s an example code:

if (Cookies.get('yourCookieName')) {
    // The cookie exists
} else {
    // The cookie doesn't exist
}

While checking if a cookie exists looks easy, there are a few considerations to keep in mind to assure success:

Read also: Longest-substring-without-repeating-characters JavaScript

When naming your cookies, select names that are clear and succinct. This not only makes your code more readable but also lessens the chances of naming conflicts with other cookies.

Proper Scope

Cookies have scope based on their path and domain. Make sure that your cookie is set to a proper path and domain to prevent issues when checking for its existence.

Sometimes, cookies may expire or be intentionally removed. Always consider the situation where a cookie you are checking for might not exist, and have a plan for handling that situation easily.

FAQs

Can I use vanilla JavaScript to check for cookie existence?

Certainly! Method 1 outlined above demonstrates how to obtain this using pure JavaScript.

Is there a maximum limit to the number of cookies I can create?

Yes, there is a limit to the number of cookies a website can store. Typically, this limit is around 20 cookies per domain.

How do I delete a cookie if it exists?

To delete a cookie, you can set its expiration date to a time in the past. This effectively removes the cookie from the user’s browser.

Can I use cookies for storing sensitive information?

It’s not supported to store sensitive information, such as passwords, in cookies due to security risks. Always prioritize security when handling user data.

Conclusion

In conclusion, mastering the art of checking if a cookie exists using JavaScript is an important skill for any web developer.

Whether you are personalizing user experiences or managing user preferences, cookies play an important role.

With the methods outlined in this article, you’ll be able to smoothly check for the existence of cookies on your website.

Remember to choose descriptive cookie names, ensure proper scope, and plan for situations where cookies might not exist.

By following best practices, you will improve user interactions and provide a more specific browsing experience.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →

Leave a Comment