r/javascript • • Nov 28 '14

Every Possible Way to Define a Javascript Function

http://www.bryanbraun.com/2014/11/27/every-possible-way-to-define-a-javascript-function
4 Upvotes

12 comments sorted by

28

u/ImPigBoT Nov 28 '14

If only I could see the overflow content of the tables on my mobile device. "Front end developer" ...

6

u/kangax_ Nov 28 '14

The author seems to be very confused about difference between function declarations and function expressions. The entire first table is wrong, past 1st row.

function(num1, num2) {
  return alert(num1 + num2);
}

..is not an "anonymous function declaration". There's no such thing as anonymous function declaration. Function declaration, unlike function expression, must have an identifier (https://es5.github.io/#x13).

(function sum(num1, num2){
  return alert(num1 + num2);
}(1, 2));

..is not a function declaration either. How can you have FunctionDeclaration as part of GroupingOperator (( and )) if that operator can only contain an expression — https://es5.github.io/#x11.1.6 :)

And so on.

http://kangax.github.io/nfe/ goes into more detail on all this.

1

u/skerit Nov 28 '14

Yeah, somehow he thinks an expression has to be an assignment to a variable, but that's just not true.

Strange he didn't even test these, his unnamed declaration will throw an error.

4

u/Medieval_Peasant Nov 28 '14

Forgot about getters and setters.

({
  get a() {
    return 'a';
  }
}).a

3

u/Calabri Nov 28 '14

The title and content of this article is inaccurate. Downvote.

4

u/c4a Nov 28 '14
"function".constructor.constructor("alert(1+1);");

4

u/x-skeww Nov 28 '14

"function".constructor.constructor

Same as Function. It's just a roundabout way to get a reference to that.

2

u/[deleted] Nov 28 '14

I'm not sure what IIFE have to do with defining a function.

2

u/Isvara Nov 28 '14

Yeah, it's completely not a way of defining a function. It's just doing something with it after you've defined it.

2

u/skitch920 Nov 29 '14

Forgot about eval, even if it is similar to new Function

var func = eval('(function(a) {return a;})');

1

u/noiv Nov 29 '14

In a few cases the function constructor creates very fast functions, at least with SpiderMonkey.

0

u/brtt3000 Nov 29 '14

I am 15 and I have a blog.