27

Are the JavaScript code snippets given below some sort of function declaration? If not can someone please give an overview of what they are?

some_func = function(value) {
    // some code here
}

and

show:function(value){
   // some code here
}
Adrian
  • 6,013
  • 10
  • 47
  • 68
Anand Shah
  • 14,575
  • 16
  • 72
  • 110

8 Answers8

72

There are six ways/contexts in which to create functions:

1) Standard declarative notation (most familiar to people with C background)

function foo() {}

All the rest are function expressions:

2) As a method of an object literal

var obj = {
    foo: function() {}
};

3) As a method of an instantiated object (created each time new is exectued)

var Obj = function() {
    this.foo = function() {};
};

4) As a method of a prototype (created only once, regardless of how many times new is executed)

var Obj = function() {};
Obj.prototype.foo = function() {};

5) As an anonymous function with a reference (same effect as #1) *

var foo = function() {};

6) As an immediately executed anonymous function (completely anonymous)

(function() {})();

* When I look at this statement, I consider the result. As such, I don't really consider these as anonymous, because a reference is immediately created to the function and is therefore no longer anonymous. But it's all the same to most people.

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
  • Is there a reason to prefer #1 or #5? I see #5 in a lot of libaries, and occasionally #1. – EsTeGe Aug 05 '12 at 14:57
  • 6
    Never mind, I found the answer myself here: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ – EsTeGe Aug 05 '12 at 15:11
  • 2
    It is misleading to suggest #1 and #5 are effectively the same, they are very different. As well as the link provided by EsTeGe, also check the excellent answer to this SO question which explains very well the difference: http://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order – terraling Feb 09 '14 at 12:44
25

The first one is simply creating an anonymous function and assigning it to a variable some_func. So using some_func() will call the function.

The second one should be part of an object notation

var obj = {
  show:function(value){
    // some code here
  }
};

So, obj.show() will call the function

In both cases, you are creating an anonymous function. But in the first case, you are simply assigning it to a variable. Whereas in the second case you are assigning it as a member of an object (possibly among many others).

  • The outer parenthesis on `obj` are superfluous – Justin Johnson Dec 08 '09 at 10:46
  • 1
    Oh! A reply to one of my posts in SO about writing code using the module pattern said that without those parenthesis, sometimes anonymous functions might fail. I still didn't get an explanation as to why. Not sure whether they apply only to module patterns or all anonymous functions. That is why I added them. –  Dec 08 '09 at 10:49
  • I think its only when you eval an object like `eval("({a:1})")` – YOU Dec 08 '09 at 10:50
  • I think @S.Mark is right. I've never seen the problem that you described in the other post. I wouldn't worry about it until it's actually a problem. Dev 1: "Why do we do abc?" Dev 2: "....because we've always done abc..." – Justin Johnson Dec 08 '09 at 11:03
  • 5
    The parentheses are necessary for functions that are invoked immediately, not object literals. A function declaration and a function expression are not the same thing, with the key point being that a function declaration cannot be invoked immediately. For example `(function() {})()` is a self-invoking function expression; the parentheses around `function(){}` are necessary to turn it into a function expression. Otherwise it is seen as a function declaration, on which the lack of an identifier (or, if an identifier is provided, the following `()`) would be a syntax error. – NickFitz Dec 08 '09 at 14:16
  • Hence it is applied in the module pattern where you evoke it after you declare it. Thanks for clearing that up! :) –  Dec 08 '09 at 15:23
4

First is local (or global) variable with assigned anonymous function.

var some_name = function(val) {};
some_name(42);

Second is property of some object (or function with label in front of it) with assigned anonymous function.

var obj = {
    show: function(val) {},
    // ...
};
obj.show(42);

Functions are first-class citizens in JavaScript, so you could assign them to variables and call those functions from variable.

You can even declare function with other name than variable which that function will be assigned to. It is handy when you want to define recursive methods, for example instead of this:

var obj = {
    show: function(val) {
        if (val > 0) { this.show(val-1); }
        print(val);
    }
};

you could write:

var obj = {
    show: function f(val) {
        if (val > 0) { f(val-1); }
        print(val);
    }
};
MBO
  • 30,379
  • 5
  • 50
  • 52
2

One way of doing it:

var some_func = function(value) {  
    // some code here
}

Another way:

function some_funct() {
}

Yet another way:

var some_object={};
some_object["some_func"] = function() {};

or:

var some_object={};
some_object.some_func = function() {};

In other words, they are many ways to declare a function in JS.


Your second example is not correct.

jldupont
  • 93,734
  • 56
  • 203
  • 318
1

The first one is a function declaration assigned to a variable (at least it should be, despite the fact that it's missing the variable type declaration first), the second one is probably related to a object declaration.

yoda
  • 10,834
  • 19
  • 64
  • 92
  • Second form is sometimes used in object literals: `some_obj = { init: function() {}, show: function() {} };` – MBO Dec 08 '09 at 10:37
1

They are called anonymous functions; you can read more about them here:

http://www.ejball.com/EdAtWork/2005/03/28/JavaScriptAnonymousFunctions.aspx

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

The first example creates a global variable (if a local variable of that name doesn't already exist) called some_func, and assigns a function to it, so that some_func() may be invoked.

The second example is a function declaration inside an object. it assigns a function as the value of the show property of an object:

var myObj = {
    propString: "abc",
    propFunction: function() { alert('test'); }
};

myObj.propFunction();
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • d'oh. thanks for noticing. if *that* would've been what i meant to write, i would not have addressed the actual question :D – David Hedlund Dec 08 '09 at 11:29
0

The first one...

some_func = function(value) {  
    // some code here
}

is declaring a variable and assigned an anonymous function to it, which is equivalent to...

function some_func (value) {  
    // some code here
}

The second one should look like this...

obj = {
    show:function(value){
       // some code here
    }
}
// obj.show(value)

and equivalent to...

//pseudo code
class MyClass {
    function show (value) {
        // some code here
    }
}
obj = new MyClass();    // obj.show(value)

Cheers

Ei Maung
  • 7,013
  • 5
  • 23
  • 23
  • Your last two examples are not equivalent since you cannot instantiate object literals (error: "TypeError: obj is not a constructor"). `var Obj = function() { this.show = function() {}; }` is equivalent to your pseudo code. – Justin Johnson Dec 08 '09 at 10:58
  • @Justin Johnson - Oh! Really? Then, why this work perfectly? `obj={show:function(value){alert("work");}} obj.show();` – Ei Maung Dec 08 '09 at 11:08
  • Yes really. I didn't say that `obj.show()` doesn't work, I said that your examples are not equivalent. – Justin Johnson Dec 08 '09 at 11:14