1

While making several test projects for my small library of code I have come across many tutorials that go about making functions in many different ways.

For example:

  1. Function Declarations

    • FunctionDeclaration : function Identifier ( FormalParameterList opt ){ FunctionBody }
  2. Function Expressions

    • FunctionExpression : function Identifier opt ( FormalParameterList opt ){ FunctionBody }
  3. Anonymous Self-Executing Functions

    • (function(msg){ alert(msg); })('SO'); // alerts "SO"
  4. Anonymous Self-Executing Functions that I have seen in source code that I suspect may be incorrect but I want to make sure

    • (function(msg){ alert(msg); }('SO')); // alerts "SO", but the passed parameter appears inside the parenthesis that wrap the function, not after like I think is correct.

With all this said, I want to clear the air about a few questions I had regarding each of the types of functions.

A function declaration:

function display(){
    //this function is evaluated at parse time,
      can be called any time
}

Is it true that a function declaration (that is evaluated at parse time and does not require parenthesis after the brackets) can be overwritten by function expressions as this question seems to indicate and this source code seems to back up?:

var display = function(){
                 //this function will be called as opposed to the
                 //display() declaration (above) any time 
                 //display() is used after this variable assignment
              };

A function expression:

var display = function nameOptional(){

              };

Is the semi-colon after the bracket in function expressions that has been assigned to a variable necessary? And also, does that mean that this:

function name(){
    //...
};

is different than this:?

function name(){
    //...
}//no semi-colon

Is the first name() a function expression, and the second name() a function declaration? Or is the first name() a function expression and the second name() a function expression with an optional left-out semi-colon. Because I have read that in function expressions, the semi-colon is only recommended. What confuses me is that in a function declaration you must have an identifier, and a body. In an expression, the identifier is optional, but you must have a body. So if you have

function identifier(){
    //...body...
}

is this a declaration, or an expression since the semi-colon is not required on expressions or declarations. On expressions it is only recommended for optimum results in the case of variable assigning.

An Anonymous Self-Executing Function:

I understand how these work, but I have seen two ways of writing this, one I am almost certain is wrong. I just would like to clear this up:

(function(msg){
    alert(msg);
})("SO");

and

(function(msg){
    alert(msg);
}("SO"));

I have read that the reason an anonymous function executes is because it is wrapped in () and if you want any parameters to be passed to it, they must be added after those () and before a semi-colon tying the whole thing off, if this is true...the second anonymous function is written incorrectly...is this true?

I have read several questions that have been answered with this link and content containing this informatino

Community
  • 1
  • 1
user3412869
  • 1,395
  • 2
  • 10
  • 11
  • 2
    Have you read this? http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/ – Alexey Ten Jul 09 '14 at 06:05
  • Actually, there are only two first types. All other examples make use of function expression. – Alexey Ten Jul 09 '14 at 06:06
  • All of this is really trivial to figure out with a few hours of reading. Function declarations are hoisted to the top of the scope they are in, and added just like function expressions, but at the top of the current scope. Function expressions are hoisted like variables, that is the variable name is hoisted but the value is not set until the expression is encountered. The two IIFE's are in most cases the same, and both are valid. – adeneo Jul 09 '14 at 06:06
  • Semicolons are "optional" in javascript, and adding the semicolon makes no difference to the function declaration, it doesn't become an expression, the semicolon just closes, and basically only affects the next code block making sure it's not interpreted wrongly. – adeneo Jul 09 '14 at 06:08
  • So is it recommended to use them after all functions just to make sure that the next line of code is interpreted corrrectly? – user3412869 Jul 09 '14 at 06:11
  • I'm not sure whether I should close this as a duplicate of [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/), [Best practice for semicolon after every function in javascript?](https://stackoverflow.com/questions/1834642/) or [Location of parenthesis for auto-executing anonymous JavaScript functions?](https://stackoverflow.com/questions/3384504/) but I'm going for **too broad**. – Bergi Jul 09 '14 at 17:25
  • I suggest you read my answer to this other question: https://stackoverflow.com/questions/13965702/js-whats-the-difference-between-a-closure-and-closure/13965980#13965980 especially scroll down to the part I discuss function expressions. Your understanding of what is a function expression is incomplete – slebetman May 02 '19 at 04:48

3 Answers3

1

Only the first two types of functions you've identified here are "real". The other two are applications of function expressions.

Going through your questions in order:

Is it true that a function declaration (that is evaluated at parse time and does not require parenthesis after the brackets) can be overwritten by function expressions as this question seems to indicate and this source code seems to back up?

Yes. (Unfortunately.) Declaring a function a second time overwrites the first definition. The original function may still be accessible if a reference to it has been been assigned to a variable, though; for instance:

function a() { console.log(1); }
var a1 = a;
function a() { console.log(2); }

a1(); // outputs "1"
a();  // outputs "2"

Is the semi-colon after the bracket in function expressions that has been assigned to a variable necessary?

Generally, yes — it denotes the end of the statement, just like the semicolon in var a = 1;. It's sometimes optional, like most semicolons in Javascript, but omitting it is inadvisable.

And also, does that mean that [a function declaration with a semicolon] is different from [a function declaration without one]?

The semicolon is not required, or meaningful, at the end of a function declaration. It's actually interpreted as a standalone semicolon in between the declarations, which has no effect.

I have read that the reason an anonymous function executes is because it is wrapped in () and if you want any parameters to be passed to it, they must be added after those () and before a semi-colon tying the whole thing off, if this is true...the second anonymous function is written incorrectly...is this true?

They're both fine; it's a stylistic choice. The line has to begin with something other than function, so that it's not interpreted as a function definition, so an initial parenthesis is used, but the exact placement of the parentheses isn't significant. If we replace the whole function expression with a, the comparison is simply between (a)() and (a()); there's no real difference.

0

I think you should know about:

// Function
function Function() {}

// Generator Function
function* Function() {}

// Asynchronous Function
async function Funtion() {}

// Asynchronous Generator Function
async function* Function() {}

// Class
class Function {}
class Function extends Object {}

// Arrow Function
() => {}
double-beep
  • 5,031
  • 17
  • 33
  • 41
Lapys
  • 936
  • 2
  • 11
  • 27
0

Here are useful links that provide some details and examples, about all types of JavaScript functions:

Function declaration, Function expressions, Function expression with grouping operators, Named function expression, Immediately-Invoke Function Expression (IIFE), Function constructor, Object constructor, ES6 Arrow function, Cloures, Closure and scope ...

JavaScript Scope Context and ‘this’ under the hood

Different ways of defining functions in JavaScript (this is madness!)

Different ways of defining a function in JavaScript

JavaScript Function

6 Ways to Declare JavaScript Functions

Functions - Browser compatibility

How do JavaScript closures work?

These are articles and tutorials that I found that can help to better understand JavaScript types of functions and applications of function expressions. I hope they can help you.

S. Mayol
  • 2,565
  • 2
  • 27
  • 34