Why should I use a semicolon after every function in javascript? - javascript

I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?
function weLikeSemiColons(arg) {
// bunch of code
};
or
function unnecessary(arg) {
// bunch of code
}

Semicolons after function declarations are not necessary.
The grammar of a FunctionDeclaration is described in the specification as this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
There's no semicolon grammatically required, but might wonder why?
Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.
FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.
The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.
However, semicolons are always recommended where you use FunctionExpressions. For example:
var myFn = function () {
//...
};
(function () {
//...
})();
If you omit the semicolon after the first function in the above example, you will get completely undesired results:
var myFn = function () {
alert("Surprise!");
} // <-- No semicolon!
(function () {
//...
})();
The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.
Recommended lectures:
Named function expressions demystified (great article)
Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)

I use them after function-as-variable declarations:
var f = function() { ... };
but not after classical-style definitions:
function f() {
...
}

JS Lint is de-facto convention, and it says no semicolon after function body. See the "Semicolon" section.

Just stay consistent! They are not needed, but I personally use them because most minification techniques rely on the semi-colon (for instance, Packer).

Really just depends on your preference. I like to end lines of code with semi colons because I'm used to Java, C++, C#, etc, so I use the same standards for coding in javascript.
I don't typically end function declarations in semi colons though, but that is just my preference.
The browsers will run it either way, but maybe some day they'll come up with some stricter standards governing this.
Example of code I would write:
function handleClickEvent(e)
{
// comment
var something = true; // line of code
if (something) // code block
{
doSomething(); // function call
}
}

It's actually more than an issue of convention or consistency.
I'm fairly certain that not placing semicolons after every statement slows down the internal parser because it has to figure out where the end of the statement is. I wish I had some handy numbers for you to positively confirm that, but maybe you can google it yourself. :)
Also, when you are compressing or minifying code, a lack of semi-colons can lead to a minified version of your script that doesn't do what you wanted because all the white space goes away.

When I minified my scripts I realized that I need to use semicolon for functions which starts with equals mark. if you define a function as var, yes you need to use semicolon.
need semicolon
var x = function(){};
var x = new function(){};
this.x = function(){};
no need semicolon
function x(){}

the semicolon after a function is not necessary
using it or not, does not cause errors in your program.
however, if you plan to minify your code, then using semicolons after functions is a good idea.
say for example you have code like the one below
//file one
var one=1;
var two=2;
function tryOne(){}
function trytwo(){}
and
//file two
var one=1;
var two=2;
function tryOne(){};
function trytwo(){};
when you minify the both, you will get the following as output
Note that comments are just for ilustration
//file one
var one=1;var two=2;function tryOne(){}
function trytwo(){}
and
//file two
var one=1;var two=2;function tryOne(){};function trytwo(){};

Edit:
It doesn't matter with ECMAScript 2021 (ES2021) so please ignore the below statement.
It is a good practice to leave the semicolons ; after the end of function braces. They have been considered a best practice.
One advantage of always using them is if you want to minify your JavaScript.
As minifying the Javascript, helps to reduce the file size a bit.
But as for the best practise and answer above, not recommended to use it after a function tag.

Related

Lets Play A Little Game!! Why am I getting an Uncaught Type Error? :) [duplicate]

I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?
function weLikeSemiColons(arg) {
// bunch of code
};
or
function unnecessary(arg) {
// bunch of code
}
Semicolons after function declarations are not necessary.
The grammar of a FunctionDeclaration is described in the specification as this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
There's no semicolon grammatically required, but might wonder why?
Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.
FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.
The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.
However, semicolons are always recommended where you use FunctionExpressions. For example:
var myFn = function () {
//...
};
(function () {
//...
})();
If you omit the semicolon after the first function in the above example, you will get completely undesired results:
var myFn = function () {
alert("Surprise!");
} // <-- No semicolon!
(function () {
//...
})();
The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.
Recommended lectures:
Named function expressions demystified (great article)
Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)
I use them after function-as-variable declarations:
var f = function() { ... };
but not after classical-style definitions:
function f() {
...
}
JS Lint is de-facto convention, and it says no semicolon after function body. See the "Semicolon" section.
Just stay consistent! They are not needed, but I personally use them because most minification techniques rely on the semi-colon (for instance, Packer).
Really just depends on your preference. I like to end lines of code with semi colons because I'm used to Java, C++, C#, etc, so I use the same standards for coding in javascript.
I don't typically end function declarations in semi colons though, but that is just my preference.
The browsers will run it either way, but maybe some day they'll come up with some stricter standards governing this.
Example of code I would write:
function handleClickEvent(e)
{
// comment
var something = true; // line of code
if (something) // code block
{
doSomething(); // function call
}
}
It's actually more than an issue of convention or consistency.
I'm fairly certain that not placing semicolons after every statement slows down the internal parser because it has to figure out where the end of the statement is. I wish I had some handy numbers for you to positively confirm that, but maybe you can google it yourself. :)
Also, when you are compressing or minifying code, a lack of semi-colons can lead to a minified version of your script that doesn't do what you wanted because all the white space goes away.
When I minified my scripts I realized that I need to use semicolon for functions which starts with equals mark. if you define a function as var, yes you need to use semicolon.
need semicolon
var x = function(){};
var x = new function(){};
this.x = function(){};
no need semicolon
function x(){}
the semicolon after a function is not necessary
using it or not, does not cause errors in your program.
however, if you plan to minify your code, then using semicolons after functions is a good idea.
say for example you have code like the one below
//file one
var one=1;
var two=2;
function tryOne(){}
function trytwo(){}
and
//file two
var one=1;
var two=2;
function tryOne(){};
function trytwo(){};
when you minify the both, you will get the following as output
Note that comments are just for ilustration
//file one
var one=1;var two=2;function tryOne(){}
function trytwo(){}
and
//file two
var one=1;var two=2;function tryOne(){};function trytwo(){};
Edit:
It doesn't matter with ECMAScript 2021 (ES2021) so please ignore the below statement.
It is a good practice to leave the semicolons ; after the end of function braces. They have been considered a best practice.
One advantage of always using them is if you want to minify your JavaScript.
As minifying the Javascript, helps to reduce the file size a bit.
But as for the best practise and answer above, not recommended to use it after a function tag.

Why are parentheses required around JavaScript IIFE? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 7 years ago.
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());
works great, but
function() {var msg='I love JavaScript'; console.log(msg);}();
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.
A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.
Now, you may have seen people saying that the following is a function expression:
var x = function () {};
It may be tempting to conclude that the syntax:
function () {};
is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:
var x = ...
That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.
Some of the forms of expressions in JavaScript include:
everything to the right of an = operator
things in braces () that are not function call braces
everything to the right of a math operator (+,-,*,/)
all the arguments to the ternary operator .. ? .. : ..
When you write:
function () {}
it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.
But when you write:
(function () {})
it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).
Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):
tmp=function(){}()
+function(){}()
-function(){}()
0/function(){}()
0*function(){}()
0?0:function(){}()
(function(){}())
(function(){})()
You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
For more detailed explanation please see:
Advanced JavaScript: Why is this function wrapped in parentheses?
HINT:
The invocation operator (()) only works with expressions, not declarations.
This will be a long-winded answer, but will give you the necessary background. In JavaScript there are two ways functions can be defined:
A function definition (the classical kind)
function foo() {
//why do we always use
}
and then the more obscure type, a function expression
var bar = function() {
//foo and bar
};
In essence the same thing is going on at execution. A function object is created, memory is allocated, and an identifier is bound to the function. The difference is in the syntax. The former is itself a statement which declares a new function, the latter is an expression.
The function expression gives us the ability to insert a function any place where a normal expression would be expected. This lends its way to anonymous functions and callbacks. Take for instance
setTimeout(500, function() {
//for examples
});
Here, the anonymous function will execute whenever setTimeout says so. If we want to execute a function expression immediately, however, we need to ensure the syntax is recognizable as an expression, otherwise we have ambiguity as to whether of not we mean a function expression or statement.
var fourteen = function sumOfSquares() {
var value = 0;
for (var i = 0; i < 4; i++)
value += i * i;
return value;
}();
Here sumOfSquares is immediately invoked because it can be recognized as an expression. fourteen becomes 14 and sumOfSquares is garbage-collected. In your example, the grouping operator () coerces its content into an expression, therefore the function is an expression and can be called immediately as such.
One important thing to note about the difference between my first foo and bar example though is hoisting. If you don't know what that it is, a quick Google search or two should tell you, but the quick and dirty definition is that hoisting is JavaScript's behavior to bring declarations (variables and functions) to the top of a scope. These declarations usually only hoist the identifier but not its initialized value, so the entire scope will be able to see the variable/function before it is assigned a value.
With function definitions this is not the case, here the entire declaration is hoisted and will be visible throughout the containing scope.
console.log("lose your " + function() {
fiz(); //will execute fiz
buzz(); //throws TypeError
function fiz() {
console.log("lose your scoping,");
}
var buzz = function() {
console.log("and win forever");
};
return "sanity";
}()); //prints "lose your scoping, lose your sanity"

Why is a function declaration not a statement while a variable declaration is

It seems like a stupid question but I really can't wrap my head around it. I began to wonder this when I was thinking of why there is a semicolon after variable declaration but not function declaration. So does that mean a function declaration is an expression?
And what is the official meaning for statement? I've been finding the answer saying that a statement is a "command" that tells computer what to do, but isn't a function declaration telling the computer what to do? Does it have something to do with when it's get loaded when executing the code?
I began to wonder this when I was thinking of why there is a semicolon after variable declaration but not function declaration
Not every statement ends with a semicolon.
Examples of statements with trailing semicolon:
Variable declaration: var foo = <expression>;
Expression statement: <expression>;
Do while loop: do <statement> while (<expression>);
Examples without trailing semicolons:
If statement: if (<expression>) <statement>
Try catch statement: try <block> catch (<identifier>) <block>
For loop: for (...) <statement>
Block statement: { <statement list> }
So does that mean a function declaration is an expression?
No, it's more complicated than that. Function declarations are not statements. They are not expressions either, they are source elements. Statements and function declarations are both source elements. **
And what is the official meaning for statement?
I can't tell you the official definition, but in the context of JS I would say something like "it's an instruction that does not produce an assignable result/value". Expressions on the other hand produce a result that can be used in other expressions.
** Good to know, but a bit off-topic: Since function declarations are not statements, they are technically not allowed to be used inside blocks. This becomes even more apparent if we also consider hoisting. This example should throw a syntax error in every browser, but unfortunately it doesn't.
if (true) {
function foo() { alert('foo'); }
} else {
function foo() { alert('bar'); }
}
foo();
This leads to different behaviors in different browser. While Chrome will show bar, Firefox will show foo. Chrome just hoists both function declarations, and the second overrides the first one. Firefox interprets both declarations as something like a function expression.
Try it yourself in different browsers.
A variable declaration can have side-effects (eg, var x = alert(42);).
A function declaration cannot.

Using eval to execute functions

There is something I don't understand about how eval works.
Suppose I have a function foo:
function foo() {
console.log("test");
}
And then I write
eval("foo()");
or
eval("foo" + "();");
The function foo is executed and I have "test" printed out.
However, if I write:
eval("function foo() { console.log(\"foo\"); }();");
or
eval("function foo() { console.log(\"foo\"); }" + "();");
I get "SyntaxError: Unexpected token )".
Why is that? I saw that when I pass the function name it is evaluated into the function's code, so I though it's supposed to be the same as "eval("foo" + "();");"
I'm using Chrome 27 if it makes any difference.
Because no answer is specific about why the last snippet fails, and nobody seems to be warning you for the dangers of eval:
eval, according to MDN:
A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
Your string, "function foo(){console.log('foo');}()" actually consists of 2 statements, that make no sense to the JS engine. Well, the second one doesn't:
function foo(){console.log('foo');}//function declaration, fine
;//<-- js adds implied statement terminator
()//no invocation, because no function reference, group nothing ==> does not compute, raise error
That's why you have to turn your function declaration statement into an expression, by adding an operator. Typically, this is the grouping operator: ()
(function foo(){ console.log('foo')});
The function declaration is now an expression, everything (the grouping () included) can be seen as a statement, unless the code that follows belongs to the code above. In this case, the invoking parentheses clearly do, so the JS engine sorts it out for you.
For clarity, some say the preferred notation is:
(function f(){}());//<-- invoking parentheses inside group
Which makes sense, because the invocation is part of the statement, after all.
If you don't like all these parentheses, any operator will do:
~function(){}();//bitwise not
+function(){}();//coerce to number
Are all equally valid. Note that they will change the possible return values of the function expression.
(function(){}());//resolves to undefined
+function(){}();//resolves to NaN, because undefined is NotANumber
How your eval could look, then, is any of the following:
eval("(function (){console.log('foo');}());");
eval("~function (){console.log('foo');}();");
eval("!function (){console.log('foo');}();");
And so on, and so forth...
Lastly, eval evaluates code in the global scope, so any code eval-ed containing functions can, and likely will, polute the global namespace. Mallicious code will also have access to everything, so be weary of XSS attacks and all other JS based techniques.
Bottom line, eval is evil, especially since all browsers now support JSON.parse natively, and for those that don't, there still is a tried and tested JSON2.js file out there.
Using eval in strict mode does make things slightly safer, but doesn't prevent XSS attacks at all, the code can still manipulate the DOM, for example, and reassign exposed DOM references or objects.
Google "why eval is evil" if you want to find out more.
Also check the ECMAScript specs
function x() {} is a statement, whereas everything else you're doing is an expression, and you can only evaluate expressions.
The other answers explain how you can turn this statement into an expression. Thought I'd let you know why you actually get an error, though. :)
eval("(function() { console.log(\"foo\"); })()");
This is called a self-executing anonymous function.
you would need to call
eval("function foo() { console.log(\"foo\"); };" + " foo();");
in order for this to work;
Put brackets around your function
eval("(function foo() { console.log(\"foo\"); })()");
It is like calling
(function foo() { console.log("foo"); })()
The main thing you should understand about eval is that it is evil. Don't use it... ever. There is always a way to achieve the same thing by dynamically creating a script document or by using a closure.
Read Douglas Crockford: JavaScript the good parts.

How should I declare my self-calling function?

I've seen self-calling functions in Javascript written like this:
(function () {
// foo!
})();
But I've also seen them written like this:
(function () {
// bar!
}());
Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?
One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:
function () {
// shut the front door! saved two characters right there!
}();
It hurts readability a good deal though.
First:
There is, like you assumed, absolutely no difference between the first two version of your self-invoking anonymous function. No browser klinks, quirks, just comes down to personal preference (Douglas Crockford calls the latter form "dog balls" by the way).
Second:
function() {
}()
will not work by design, since that statement creates a function statement/declaration. You need a function expression to immediately invoke itself. To create a function expression you can do multiple things. Putting the whole statement into parenthesis is one way, but you could also write
!function() {
}()
or
+function() {
}
All of these operators will make an expression.
The first two are identical, but if I remember correctly, one of them is preferred by jsLint (I think it’s the second).
The third raises a syntax error in most interpreters, but there are other variants:
!function() {
alert('I’m executing myself!');
}();
var noname = function() {
alert(noname); // undefined!
}();
​
You can replace the ! with a + or - ( None of them will make Crockford happy )
This is mostly a convention issue.
(function () {}()); <- one less stack frame before execution (maybe)
(function () {})(); <- executed outside the parenthesis, so one tiny little frame before execution, although I don't like this style, IMO it's visually disconnected.
function () {}(); <- this is just bad practice IMO, it's not immediately obvious that this is an IIFE which is mostly due to convention, but this also has the problem that if you forget a semi-colon before the expression it will, under some conditions silently assign variables the value undefined.
Example:
var x = 0,
y = 1,
z = 3,
function () {
alert("Z is now undefined, instead of throwing a syntax error.");
}();
As mentioned by Andre Meinhold, this is not in expression position.
Pragmatically speaking, JSLint will complain about the first and prefer the second format. Beyond that, it's really personal preference and consistency is key here.
The third format will result in a SyntaxError, so you can't use that. That's because your creating a function declaration, not a function expression. It's the function expression that you're calling when you use the immediate function pattern.
Crockford says to use (function () {...}()).
It's just a stylistic choice, but it's in the community's interest to agree upon a convention and (at the risk of starting a flame-war) why not use Crockford's?
Also, keep in mind that (function () { }()); adds potential confusion. Since in a long function, someone not paying attention might see two closing parentheses and only one being opened.

Categories