Why doesn't JavaScript require semicolons after function declarations? [duplicate] - javascript

This question already has answers here:
Why should I use a semicolon after every function in javascript?
(9 answers)
Closed 7 years ago.
A student asked me why JavaScript requires semicolons after variable declarations but not after function declarations and I didn't really have a good answer.
For example, these variable declarations (including the one holding a function) are followed by semicolons...
var x = 5;
var test = function() { return null; };
But this function declaration has no semicolon afterwards nor should it. Why? What is the logic behind the differentiation? Why does variable assignment require a semicolon but function declaration does not?
function test {
return null;
}

Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.

Well, semicolons after function deceleration aren't required.
The answer is pretty simple.
Semicolons are used in JavaScript on order to separate statements.
So function declarations aren't statements.
Edit:
Oh, #Basil Baby, was faster :P

Related

Why do I have to put a semicolon before a self executing anonymous function? [duplicate]

This question already has answers here:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Closed 5 years ago.
Most of the cases Javascript permits us to omit a semicolon in the end of a statement. However, interestingly, not in this case:
var x = [5, 'asdf']
(function() {
window.alert("Yay!")
})()
This won't work, unless we put one semicolon in the end of the statement preceding the anon function:
var x = [5, 'asdf'];
(function() {
window.alert("Yay!")
})()
Now it works perfectly.
What obscure rule governing implied semicolons in the ends of statements prescribes that in this case this one semicolon is not implied?
Uncaught TypeError: [5,\"asdf\"] is not a function
According to the error it considers that your [5, 'asdf'] is an function name, and you tries to execute it passing the parameters. If we join them in one line, you can see that it is similar to the function call with passed parameter as function
[5, 'asdf'](function() { window.alert("Yay!") })
So putting semicolon says to the compiler that the statement ends, and the next line is another statement which is IIFE.

What's the difference between these two IIFE invocation syntaxes? [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 7 years ago.
(function f() {
// do something
}());
vs
(function g() {
// do something
})();
Note the position of the ending parentheses.
Do these execute in the same manner?
Do they restrict the scope of variables differently?
They are the same. Just two notations to do the same thing.
Some people find one notation more intuitive than the other. Just a matter of preference, nothing more than that.

Is the underscore.js IIFE syntax valid? [duplicate]

This question already has answers here:
Reason behind this self invoking anonymous function variant
(5 answers)
Closed 8 years ago.
I just took a look at the underscore.js source code and when i strip the source code down to its bare containing IIFE it looks like this:
(function() {
}.call(this));
I always used the syntax with outer parantheses (function() {}).call(this); and wondered if this syntax is also valid and common?
If you're asking about the location of the outer ) specifically, then whether it's located immediately after the closing brace or after the entire expression doesn't matter for the most part. Either way doesn't make a difference to how the IIFE is executed.
The only difference here is the .call(this), which is invoked as a member of the function expression — a typical IIFE has just the inner parentheses immediately following the closing brace. The reason .call(this) is used is detailed in a number of other answers including this one.

What is the difference between these two? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Are named functions preferred over anonymous functions in JavaScript? [duplicate]
(4 answers)
Closed 9 years ago.
I saw the following JavaScript functions works exactly same, Then what is the difference between them other than syntax.
The function are:
var functionName=function(){
//some code here
};
function functionName(){
//some code here
}
I call them in the same way as:
functionName();
Please dont' tell me there syntax is different, Other than that is there any difference like
1)speed of execution
2)Memory utilization etc.
Thanks in advance!
This has been answered many times in StackOverflow. It is just the way of naming. So taking up some points from the answers, I would say:
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there.
Advantages & Disadvantages:
There are few advantages to naming functions:
names for meta analysis. functionInstance.name will show you the name.
Far more importantly, the name will be printed in stack traces.
names also help write self documenting or literate code.
There is a single disadvantage to named functions expressions
IE has memory leaks for NFE
Another main difference
The difference is that functionTwo is defined at parse-time for a script block, whereas functionOne is defined at run-time. For example:
<script>
// Error
functionOne();
var functionOne = function() {
}
</script>
<script>
// No error
functionTwo();
function functionTwo() {
}
</script>
References
var functionName = function() {} vs function functionName() {}
Are named functions or anonymous functions preferred in JavaScript?
Named function expressions demystified
Function Declarations vs. Function Expressions.
var functionName = function() {} vs function functionName() {}
1st one is Named Function Expressions, which should return some value to the caller.
2nd one is just a function, it's upto you whether you return value or not

what does !function in Javascript mean? [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.
Here is how Twitter uses it:
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
from https://twitter.com/about/resources/buttons#
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use + instead of !.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
Function Declarations vs. Function Expressions
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.

Categories

Resources