Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

what is this code mean?

Status
Not open for further replies.

cat5ives

Programmer
Sep 13, 2011
11
US
I'm trying to learn javascript from w3schools's website. I don't understand the code in red below. Is the code correct (are those 2 lines suppose to be 1 statement, the 1st semi colon should not be there)?

Thanks in advance.

Code:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
[COLOR=#EF2929]var c_value=escape(value) + ((exdays==null) ? "" : "[COLOR=#204A87];[/color]
expires="+exdate.toUTCString());[/color]

document.cookie=c_name + "=" + c_value;
}

setCookie("username",username,365);
 
Hi

That is one line. The semicolon ( ; ) is part of the string.

Maybe this way is more evident :
JavaScript:
[b]function[/b] [COLOR=darkgoldenrod]setCookie[/color][teal]([/teal]c_name[teal],[/teal]value[teal],[/teal]exdays[teal])[/teal]
[teal]{[/teal]
  [b]var[/b] exdate[teal]=[/teal][b]new[/b] [COLOR=darkgoldenrod]Date[/color][teal]();[/teal]
  exdate[teal].[/teal][COLOR=darkgoldenrod]setDate[/color][teal]([/teal]exdate[teal].[/teal][COLOR=darkgoldenrod]getDate[/color][teal]()[/teal] [teal]+[/teal] exdays[teal]);[/teal]
  [b]var[/b] c_value[teal]=[/teal][COLOR=darkgoldenrod]escape[/color][teal]([/teal]value[teal])[/teal] [teal]+[/teal] [teal](([/teal]exdays[teal]==[/teal][b]null[/b][teal])[/teal] [teal]?[/teal] [green][i]""[/i][/green] [teal]:[/teal] [green][i]"; expires="[/i][/green][teal]+[/teal]exdate[teal].[/teal][COLOR=darkgoldenrod]toUTCString[/color][teal]());[/teal]

  document[teal].[/teal]cookie[teal]=[/teal]c_name [teal]+[/teal] [green][i]"="[/i][/green] [teal]+[/teal] c_value[teal];[/teal]
[teal]}[/teal]

Feherke.
[link feherke.github.com/][/url]
 
the conditional operator is shorthand for the IF statement, so :

Code:
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
[code]

is the same as this longhand version

[code]
var c_value;
if ( exdays == null ) 
{
    c_value = escape(value);
}
else
{
   c_value = escape(value) + "; expires="+exdate.toUTCString()"; 
}

Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005 & 2006
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top