JavaScript Cookies Write

You are Here:

JavaScript Cookies Write

The document.cookie property writes a cookie to the web browser.

Note: Though you set a String value to the document.cookie property, when you read it out again, you can only see the key-value pair of it.

Write Single Cookie

In the following example, we will write a single cookie (username).


HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var name = "Steve"; document.cookie = "username="+name+";path=/"; document.write("Cookie written"); </script> </body> </html>

Write Multiple Cookies

There are no shortcuts to write multiple cookies, you have to set document.cookie property multiple times.


HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var num1 = 1; var num2 = 2; document.cookie = "cookie1="+num1+";path=/"; document.cookie = "cookie2="+num2+";path=/"; document.write("Cookie written"); </script> </body> </html>

Write Object Cookie

To write an object to a cookie, you have to convert that Object to a String and then store it.


HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var bike = { company: "honda", model: "CBR 1000RR", color: "Red" }; document.cookie = "objectCookie="+JSON.stringify(bike)+";path=/"; document.write("Cookie written"); </script> </body> </html>


Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author