Explain Codes LogoExplain Codes Logo

What is the shortest function for reading a cookie by name in JavaScript?

javascript
regex
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Mar 12, 2025
TLDR
function getCookie(name) { // Looks for a match, like a seasoned detective🕵️‍♂️ let match = document.cookie.match(`(?:^|; )${name}=([^;]*)`); // If found, "uncodes" it. If not, returns undefined. Simple, isn't it? 😉 return match ? decodeURIComponent(match[1]) : undefined; }

Here is the function getCookie(name) - lean, mean, and efficient! Pass in the name of the cookie you're after, and it hands you the value. If it doesn't find anything, it gives back undefined. This one-liner specializes in plowing through the document.cookie's string, with a surgical precision delivered by regex.

Regex for speed, not loops

Opting for regex is like choosing a jet to cut through the crowded skies instead of a slow bicycle. With regex, you can instantly tap into the document.cookie string, find your specific cookie and return, avoiding the unnecessary extra mileage of looping through every value.

Compliant as per internet standards

Our function is compliant with RFC 2109, just like a model student adhering to school rules. It ensures excellent compatibility with complex cookie structures and guarantees proper character encoding for maximum cookie reliability.

Using modern JavaScript features

Embrace the modern JavaScript features of arrow functions and optional chaining. These help to compress functions into a more compact form without losing any of the original bite.

Cache like a boss

If the function is called numerous times, storing the cookie values in an object map could enhance performance. This is like having a personal librarian who knows exactly where to find the book you are looking for.

Guarding the legacy

While riding the wave of modern JavaScript syntax, don't forget the older browsers that may not support these features. It's important to make our function useful across various environments, keeping it accessible and usable.

Performance optimization

Make getCookie a global function to dodge repeated interpretation and the ensuing performance delay. Let's be honest, as much as we love our JavaScript, we don't want it to start behaving like a sluggish snail🐌!

Escape the special characters

Remember, cookies can contain special characters. Regex is your knight in shining armor, coming to the rescue by accurately parsing these characters! encodeURIComponent and decodeURIComponent are two trusty foot soldiers in such a situation, always ready to maintain your data's integrity.

Say no to stale data

Storing cookies may seem like a great idea but beware of stale data. Ensure real-time accuracy by avoiding cache wherever possible, even if it's at the cost of performance. Remember, it's all about striking the right balance.

Ready for a more compact function?

Let's balance between compactness and efficiency. We could even aim for a tiny function, 89 bytes like the one here:

const c = n => (document.cookie.match(`(?:^|; )${n}=([^;]*)`)||[])[1] || undefined;

Though it's bite-size, it retains core functionality, and that's what we're here for, aren't we?

Tried-and-tested methods

Don't forget to pay homage to the wisdom of the ancients; sources like QuirksMode.org or jQuery.cookie provide time-tested, familiar patterns, providing the right solution for different project requirements.