Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are named functions preferred over anonymous functions in JavaScript? [duplicate]

Tags:

javascript

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

There are two possible methods for pulling out a function in Javascript:

var foo = function() { ... } 

This is a bit contrived; another common pattern is:

var foo = {    baz: 43,    doSomething: function() {        // ...    } } 

versus

function foo() {    // ...  } 

Is there an explicit reason to prefer one or the other?

like image 940
Billy ONeal Avatar asked Apr 10 '12 00:04

Billy ONeal


People also ask

What is the difference between anonymous and named functions in JavaScript?

Anonymous functions are never hoisted (loaded into memory at compilation). Named functions are hoisted (loaded into memory at compilation). When invoking an anonymous function, you can only call it after the declaration line. A name function can be invoked before declaration.

Does JavaScript support named function and anonymous function?

As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function.

What are the benefits of using named functions in your listeners?

A named function helps keep your code more DRY (an acronym for Don't Repeat Yourself). Second, you can remove them later if you want using removeEventListener() . You cannot do this with anonymous functions.

What is the benefit of anonymous function in JavaScript?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.


2 Answers

It all comes down to preference to where you declare your functions; hoisting.

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. This means that code like this:

function foo() {     bar();     var x = 1; } 

is actually interpreted like this:

function foo() {     var x;     bar();     x = 1; } 

Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted. This is not the case with function declarations, where the entire function body will be hoisted as well.

function test() {     foo(); // TypeError "foo is not a function"     bar(); // "this will run!"     var foo = function () { // function expression assigned to local variable 'foo'         alert("this won't run!");     }     function bar() { // function declaration, given the name 'bar'         alert("this will run!");     } } test(); 

In this case, only the function declaration has its body hoisted to the top. The name 'foo' is hoisted, but the body is left behind, to be assigned during execution.

You can give names to functions defined in function expressions, with syntax like a function declaration. This does not make it a function declaration, and the name is not brought into scope, nor is the body hoisted.

foo(); // TypeError "foo is not a function" bar(); // valid baz(); // TypeError "baz is not a function" bin(); // ReferenceError "bin is not defined"  var foo = function () {}; // anonymous function expression ('foo' gets hoisted) function bar() {}; // function declaration ('bar' and the function body get hoisted) var baz = function bin() {}; // named function expression (only 'baz' gets hoisted)  foo(); // valid bar(); // valid baz(); // valid bin(); // ReferenceError "bin is not defined" 

So, if your preference is to have functions hoist to the top use a function declaration otherwise use expression. I prefer the latter as I typically build object literals with methods as function expressions.

Named function expressions can be handy when errors are thrown. The console will tell you what the function is instead of stating anonymous aka stack trace.

like image 121
Trevor Avatar answered Oct 11 '22 16:10

Trevor


You've hit on a couple different things here, but I'll try to hit your main question first.

In general....

function() { ... } is a function expression. Syntaxically this is on the same level as 2 or [4,5]. This represents a value. So doing var foo=function(){ ... } will work as planned, every time.

function foo() { ... } is a function declaration. This might seem to do the same thing as var foo=function(){...}, but there's a small caveat. As its a declaration, it works similar to the concept of variable hoisting in JS (basically, all variable declarations are done before any expressions are evaluated).

A good example is from here:

function test() {     foo(); // TypeError "foo is not a function"     bar(); // "this will run!"     var foo = function () { // function expression assigned to local variable 'foo'         alert("this won't run!");     }     function bar() { // function declaration, given the name 'bar'         alert("this will run!");     } } test(); 

Basically variable hoisting has brought the value up to the top, so this code is equivalent (in theory) to :

function test() {     var foo;//foo hoisted to top     var bar=function(){//this as well         alert("this will run!");     }      foo(); // TypeError "foo is not a function"     bar(); // "this will run!"     var foo = function () { // function expression assigned to local variable 'foo'         alert("this won't run!");     } } 

NB: I'd like to take this spot to say that JS interpreters have a hard time following theory, so trusting them on somewhat iffy behaviour is not recommended. Here you'll find a good example at the end of a section where theory and practice end up not working (there are also some more details on the topic of expressions vs declarations).

Fun fact: wrapping function foo() {...} in parentheses transforms it from a declaration to an expression, which can lead to some weird looking code like

(function foo() { return 1; })();// 1 foo; //ReferenceError: foo is not defined 

Don't do this if you don't have a reason to, please.


Summary var foo=function(){ ... } is *sorta kinda * the same as function foo(){ ... } except that the former does what you think it does where you think it should whereas the latter does weird stuff unless you wrap it in parens, but that messes up the scope, and JS interpreters allow you to do things that are considered syntax errors in the spec so you're led to believe that wrong things are in fact right, etc....

please use function expressions( var f=function(){...} ). There's no real reason not to, especially considering you're somewhat forced to do it when you're using dot syntax.


On to the second thing you touched.....

I'm not really sure what to say, it's kinda sorta completely different from everything else about this.

var foo = {     baz: 43,     doSomething:function() {         ...     } } 

this is known as object literal syntax. JSON, which is based off of this syntax, is a pretty neat way of formatting data, and this syntax in JS is often used to declare new objects, with singleton objects for example(avoiding all the mess with declaring a function and using new ). It can also be used in the same way XML is used, and is preferred by all the cool kids...

Anyways, basically object literal syntax works like this:

{ name1: val1, .... namek:valk } 

This expression is an object with certain values initialised on it. so doing var obj={ name1: val1, .... namek:valk } means that :

obj.name1==val1; obj['name1']==val1;// x['y'] is the same thing as x.y  ... obj.namek==valk; 

So what does this have to do with our example? Basically your expression is often used to declare singleton objects. But it can also be used to declare an object prototype, so someone can later do var newObj=Object.create(foo) , and newObj will have foo as a prototype.

Look into prototypal inheritence in detail if you want to really get how useful it is. Douglas Crockford talks about it in detail in one of his many talks).

like image 20
rtpg Avatar answered Oct 11 '22 16:10

rtpg