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

The shortest way to read a cookie by name in JavaScript is using a one-line function that searches through document.cookie and extracts the specific value.

Shortest Cookie Reader Function

Here's the most concise function to read a cookie by name:

<html>
<head>
    <title>Cookie Reader</title>
</head>
<body>
    <script>
        // Set some cookies first for testing
        document.cookie = "username=john; path=/";
        document.cookie = "theme=dark; path=/";
        document.cookie = "language=en; path=/";
        
        // Shortest function to read cookie by name
        function getCookie(name) {
            return document.cookie.split('; ').find(row => row.startsWith(name + '='))?.split('=')[1];
        }
        
        // Test the function
        console.log("Username:", getCookie("username"));
        console.log("Theme:", getCookie("theme"));
        console.log("Language:", getCookie("language"));
        console.log("Nonexistent:", getCookie("nonexistent"));
    </script>
</body>
</html>
Username: john
Theme: dark
Language: en
Nonexistent: undefined

How It Works

The function works by:

  • Splitting document.cookie by '; ' to get individual cookie pairs
  • Using find() to locate the cookie that starts with the given name
  • Using optional chaining ?. to handle cases where the cookie doesn't exist
  • Splitting by '=' and returning the value part

Alternative Approaches

Here are other common methods for comparison:

<html>
<head>
    <title>Cookie Reading Methods</title>
</head>
<body>
    <script>
        // Set test cookies
        document.cookie = "user=alice; path=/";
        document.cookie = "role=admin; path=/";
        
        // Method 1: Using regular expression
        function getCookieRegex(name) {
            const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
            return match ? match[2] : null;
        }
        
        // Method 2: Traditional loop approach
        function getCookieLoop(name) {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                let cookie = cookies[i].trim();
                if (cookie.indexOf(name + '=') === 0) {
                    return cookie.substring(name.length + 1);
                }
            }
            return null;
        }
        
        console.log("Regex method:", getCookieRegex("user"));
        console.log("Loop method:", getCookieLoop("role"));
    </script>
</body>
</html>
Regex method: alice
Loop method: admin

Comparison

Method Code Length Performance Browser Support
Modern (find + optional chaining) Shortest Good ES2020+
Regular Expression Medium Good All browsers
Traditional Loop Longest Best All browsers

Complete Example with Error Handling

<html>
<head>
    <title>Robust Cookie Reader</title>
</head>
<body>
    <script>
        // Enhanced version with better error handling
        function getCookie(name) {
            if (!name || !document.cookie) return null;
            
            const cookie = document.cookie
                .split('; ')
                .find(row => row.startsWith(name + '='));
            
            return cookie ? decodeURIComponent(cookie.split('=')[1]) : null;
        }
        
        // Set a cookie with encoded value
        document.cookie = "message=" + encodeURIComponent("Hello World!") + "; path=/";
        
        console.log("Decoded message:", getCookie("message"));
        console.log("Missing cookie:", getCookie("missing"));
    </script>
</body>
</html>
Decoded message: Hello World!
Missing cookie: null

Conclusion

The shortest cookie reader uses modern JavaScript features like find() and optional chaining. For maximum browser compatibility, use the traditional loop or regex approach.

Updated on: 2026-03-15T23:18:59+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements