Is it ever necessary to add a semicolon at the end of a function definition like the following
function helloWorld() {
//some code
}; //note the semicolon here at the end is it ever necessary? Ever
I have a friend that swears this is optional. I think it is never optional I have never read anything about it being optional at the end of a function. I have never seen any one ever do that "Except him". Is the semi colon optional.
var hellWorld = function (){
}; // the semicolon here it is optional because you are defining a variable this is OK and optional
Semicolons delimit expressions. You can add any amount of semicolons after one, since they'd be delimiting empty statements.
function() {
// Works.
};;;;;;;;;;;;;;;;;;;;;
That semicolon after the function is not "optional", it's plain redundant.
As for the actually optional ones, they are so because Javascript will add semicolons before newlines in most situations one is needed. These you should write explicitly. You'll be bitten by the lack of an auto-semicolon sooner or later.
In that case, yes, it's not needed.
This works fine:
function foo() {} var x = "hi";
This, however, is a syntax error:
var foo = function() {} var x = "hi";
It would be fine with a line-break after }, or with a semi-colon. You don't need both -- generally a semicolon is inserted before a line break or closing brace if the program is invalid without it. But in some cases the program still is valid without it but means something else. So you have to be careful relying on semi-colon insertion.
Example:
var x = "foo"
/foo/.test(x)
Here I wanted semi-colon insertion at the end of the first line, but got burned because the / in my RegEx could also be a division operator. So no semi-colon insertion. The fact that this is invalid when you get to the . doesn't save you, var x = "foo" / is a valid program fragment, so no semi-colon insertion.
This is why some people say "Just never rely on semi-colon insertion".
But you still don't need a semi-colon after a function definition.
Not required.It is implicitely inserted but relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that.
There are a couple places where missing semicolons are particularly dangerous:
// 1.
MyClass.prototype.myMethod = function() {
return 42;
} // No semicolon here.
(function() {
// Some initialization code wrapped in a function to create a scope for locals.
})();
var x = {
'i': 1,
'j': 2
} // No semicolon here.
// 2. Trying to do one thing on Internet Explorer and another on Firefox.
// I know you'd never write code like this, but throw me a bone.
[normalVersion, ffVersion][isIE]();
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
// 3. conditional execution a la bash
-1 == resultOfOperation() || die();
Not necessary, but good style. But when using a minifier which removes extraneous white space, shortens variables etcetera, left out semicolons often give problems.
Related
This question already has answers here:
Do you recommend using semicolons after every statement in JavaScript?
(11 answers)
Closed 6 years ago.
When executing a function in JavaScript, I've always ended my code block with a semi-colon by default, because that's what I've been taught to do. Coming from Java it felt a bit unorthodox at first, but syntax is syntax.
function semiColon(args) {
// code block here
};
or
function sloppyFunction(args) {
// code block here
}
Lately I've been seeing more and more code where the developer left the semi-colon out after functions, but the intended code still executed normally. So are they actually required? If not, why is it common practice to include them? Do they serve another purpose?
Function declarations do not need a semi-colon, though if you put a semi-colon there, it won't be harmful, it is just a redundant empty statement.
function semiColon(args) {
// code block here
};;;; // 4 empty statements
Most statements require a semi-colon, but if you leave the semi-colon out it will be inserted automatically in most cases by Automatic Semi-Colon Insertion, with caveats. In general it is easier to just always add a semi-colon after your statements, so that you, and other developers working with your code, don't have to worry about those caveats.
This code is correct:
function semiColon(args) {
// code block here
} // No need for semi-colon
var semiColon = function (args) {
// code block here
}; // Semi-colon required here
Whereas this code is wrong, but will still usually work:
function semiColon(args) {
// code block here
}; // Redundant unnecessary Empty Statement
var semiColon = function (args) {
// code block here
} // Semi-colon required here,
// but ASI will sometimes insert it for you, depending on
// the subsequent token
NO - using semicolons to end function declarations are NOT necessary in JavaScript. While they will not throw an error, they are the equivalent of using more than one semicolon to end a line of code - harmless, but unnecessary. Being superfluous, they are considered poor stylistic and programming practice.
The one exception is a function expression, e.g.
var my_function = function(a, b){ };
where you DO need the semicolon to terminate the line.
You shall not add a semicolon after a function declaration.
Because, after checking the Javascript grammar:
StatementList:
StatementListItem
StatementList
StatementListItem:
Statement
Declaration
Declaration:
HoistableDeclaration
ClassDeclaration
LexicalDeclaration
HoistableDeclaration:
FunctionDeclaration
GeneratorDeclaration
Here's the grammar production for a function:
FunctionDeclaration → HoistableDeclaration → Declaration → StatementListItem → StatementList
which proves that my former response is wrong (no need to look at the former edits, as it's wrong! ;) ).
A function xx() {} construct alone is a special case, neither — strictly speaking — a statement or an expression, and thus is NOT to be ended with a semicolon.
You only need to add a semicolon (or leave the ASI take care of it) if you're using the expression function() construct, which exists when it is part of a statement. To make it a statement you need to either have it part of a statement:
var foo = function() {};
or embedded within another expression:
(function() {})();
!function x() { ... }();
And in either cases, you need to add the semicolon at the end of the full statement, obviously.
Generally speaking, I like the python mantra "explicit is better than implicit" so when you hesitate to add a semicolon that the ASI would add otherwise, just add it.
sorry for being wrong in the first version of my answer, I'll debug some PHP code as a penitence. ☺
HTH
Why do I get the following error...
Uncaught TypeError: object is not a function
...at the following line, of a certain JS script?
(function($){
And why do I get that error only when JS are concatenated? (I'm using Gulp)
And why does it work if I add ; before that line, like that:
;(function($){
?
update
The preceding line - that is, the object which is not a function, according to the runtime error - on the concatened script was a }, as in:
storage = {
//...
}
I'm used to always put semicolon, but not after curly braces.
Turns out the curly braces could delimit the end of a statement, like in this case, and then it's recommended to use the semicolon to avoid this error. Here's a good explanation.
Javascript ignore missing semi-colon and try to interpret it. So if you don't input the semi-colon, it use the next line to see if it should end the line or chain it.
That allow you to use thing like this :
String
.split();
and it will be interpreted like that :
String.split();
But, this would also work :
String
.split
();
Now, If you have something like this :
var a = 'a';
var b = a
(function(){})
JavaScript has no way to know what you really want to do, so it will interpret it like that :
var a = 'a';
var b = a(function(){});
Giving you the error [place object type here] is not a function
Bottom line, always put your semi-colon.
Edit
After seeing your code, here how it is interpreted :
storage = {/**/}(function($){})(jQuery);
So Object ({} === Object) is not a function
When concatenated it believes you're trying to call whatever precedes the (function($) {...}.
If you put () after a reference it tries to call whatever the reference is. This is why you'll see a lot of JavaScript libraries precede their code with a lone ;
In the lodash library line, why is there a defensive semicolon on the first line?
;(function(window) {
...
}(this));
I recently read in Definitive JavaScript about defensive semicolons being used to protect against users who don't use semicolons properly, but as there is no preceding code, I don't see the point. Is this in case the library is concatenated on to the end of another library?
In case you use a javascript compressor/minifier, and the previous plugin does not have a ; at the end, you might run into troubles. So, as a precaution, ; is added.
Also, It safely allows you to append several javascript files, to serve it in a single HTTP request.
That semicolon is also used to ensure that it is not interpreted as a continuation of the previous statement:
var x = 0 // Semicolon omitted here
;[x,x+1,x+2].forEach(console.log) // Defensive ; keeps this statement separate
More detail: https://stackoverflow.com/a/20854706/1048668
'onhashchange'in(window)
Having in() work is not a surprise, as new(XMLHTTPRequest) or typeof(x) are other examples of this construct, but not having to separate the string and in is.
Is this per ECMAScript specs? It works in Chrome and FF, haven't tested IE.
From what I can tell, there's no difference whether you wrap window in parenthesis or not in this particular instance. Either way, it checks for this member on the window object.
Might be less confusing if you use spaces:
'onhashchange' in (window)
The same as
'onhashchange' in window
in is not a function, but when you remove the spaces I can see how you read it as such. One advantage to wrapping window in parenthesis is that you can then minify the code:
'onhashchange'in(window)
Something you could not do without the parenthesis.
' is a token that ends a string, so a pair of '' are semantically unambiguous, you don't need whitespace after the end of a string for the lexer to know that it has reached the end of a string.
Another way of saying that is that this works for the same reason that 'Hello '+'world' works.
Additionally, in is a keyword, not a function. It seems like you're thinking of () as the "function call operator", but in this case it's just a disambiguating parentheses.
It's like asking "why does 1 +(2) work?" + doesn't become a function just because you follow it with a paren, and similarly the following will work:
function foo(){}
foo
();
Javascript is brittle with its whitespace rules.
I'm not sure if the notation is confusing you (that maybe in() is a method?), but in is one of those elements of JS that few people correctly understand (I didn't really understand it until quite recently). This is a simplified version showing what in does:
var foo = {
'bar':1,
'barbar':2
}
console.log('bar' in foo); //true
console.log('baz' in foo); //false
What makes this all the more confusing is that you can use in inside a for() loop, as if it (in) were an iterator. The way I tend to think of for loops is like this:
for (exp1; condition; exp2) {
/* statements */
}
for (condition) {
/* statements */
}
In other words, the loop will continue until the in condition fails, which will happen when it runs out of members.
The following code illustrates an object literal being assigned, but with no semicolon afterwards:
var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?
I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that
Semicolons are not optional with statements like break/continue/throw
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.
The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:
var literal = {
say: function(msg) { alert(msg); }
}
(function() {
// ....
})();
The parser might interpret the brackets as a function call, here causing a type error, but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.
JavaScript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.
var foo = 'bar'
// Valid, foo now contains 'bar'
var bas =
{ prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb =
switch (zeb) {
...
// Invalid, because the lines following 'var zeb =' aren't an assignable value
Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown, but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:
return {
prop: 'yay!'
}
// The object literal gets returned as expected and all is well
return
{
prop: 'nay!'
}
// Oops! return by itself is a perfectly valid statement, so a semicolon
// is inserted and undefined is unexpectedly returned, rather than the object
// literal. Note that no error occurred.
Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.
I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "JavaScript: The Good Parts". I highly recommend it.
In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.
JavaScript does not have semicolons as "optional". Rather, it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like break, continue, or throw. Refer to the ECMA Language Specification for more details; specifically 11.9.1, rules of automatic semicolon insertion.
Use JSLint to keep your JavaScript clean and tidy
JSLint says:
Error:
Implied global: alert 2
Problem at line 3 character 2: Missing
semicolon.
}
The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing JavaScript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.
If you are looking at writing "correct" JavaScript, I would suggest testing things in Firefox with javascript.options.strict (accessed via about:config) set to true. It might not catch everything, but it should help you ensure your JavaScript code is more compliant.
This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from
var foo = "bar";
The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.
If you want to be writing correct JavaScript code, write the semicolon :-)
According to the ECMAscript spec, http://www.ecma-international.org/publications/standards/Ecma-262.htm, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.