I am learning to create cookies in JavaScript, I am having problems in understanding the working of last 3 lines of code. I know this Question doesn’t suits the Stackoverflow Standand but I will be grateful if anyone kindly explains it.
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : ";
expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
If exdays is not null, i.e. it is given as an argument (in JavaScript, functions can take any number of arguments), with a ternary check (if/else shorthand) it appends the string “expires=…” to the cookie string. Else, there is no expires string (it will be a session cookie).
Finally, document.cookie is modified. For more info on cookies and changing via JS, see http://www.quirksmode.org/js/cookies.html
Basically, to add a new cookie using JS, you set document.cookie = “key=value”. Other cookies are not overwritten, the new cookie is simply appended.
To delete other cookies, one needs to set an expiry date in the past and they will be cleared by the browser.
If you simply print document.cookie, you will see all cookies (technically not all, except http-only cookies etc.), but there is no way to learn their expiry dates from JavaScript.