JavaScript syntax: Difference between revisions

Content deleted Content added
m Variables: enclose="div"
Whitespace and semicolons: defensive semicolon
Tag: nowiki added
Line 16:
 
===Whitespace and semicolons===
[[Space (punctuation)|Space]]s, [[tab character|tab]]s and [[newline]]s used outside of string constants are called [[whitespace (computer science)|whitespace]]. Unlike C, whitespace in JavaScript source can directly impact semantics. Because of a technique called "automatic semicolon insertion" (ASI), some statements that are well formed when a newline is parsed will be considered complete (as if a semicolon were inserted just prior to the newline). ProgrammersSome areauthorities advisedadvise to supplysupplying statement-terminating semicolons explicitly because it may lessen unintended effects of the automatic semicolon insertion.<ref>{{cite book
|title=JavaScript: The definitive Guide
|last=Flanagan
Line 40:
// Treated as:
// a = b + c(d + e).foo();
</syntaxhighlight>
 
Alternatively, some suggest the use of ''leading'' semicolons on lines starting with ( or <nowiki>[</nowiki>, so the line is not accidentally joined with the previous one. This is known as a '''defensive semicolon''', and is particularly recommended because code may become ambiguous when it is rearranged. For example:
<syntaxhighlight lang="JavaScript">
a = b + c
;(d + e).foo()
 
// Treated as:
// a = b + c;
// (d + e).foo();
</syntaxhighlight>