4

I'm learning JavaScript and am trying to learn the proper terms for what I am doing. There are so many ways to create a function.

I have created 3 examples that do the same thing, but the functions are created in completely different ways.

My questions are:

  • Are any one of these methods better than the other?

  • Why would I choose to do one way or another?

  • What is the last "object" method called?

  • What advice would you have to make this example better?

//EXAMPLE 1
// is this called function declaration?
function add( a, b ) {
 return a + b;
}

function subtract( a, b ) {
 return a - b;
}

function compute( a, b ) {
 var sum = add( a, b );
 var difference = subtract( a, b );
 var total = sum + difference;

 return total;
}

compute( 2, 3 ); //returns 4



//EXAMPLE 2
// is this called function expressions?
var add = function ( a, b ) {
 return a + b;
};

var subtract = function ( a, b ) {
 return a - b;
};

var compute = function ( a, b ) {
 var sum = add( a, b );
 var difference = subtract( a, b );
 var total = sum + difference;

 return total;
};

compute( 2, 3 ); //returns 4




//EXAMPLE 3
// what is this method called?
var calculator = {
 add: function ( a, b ) {
  return a + b;
 },
 subtract: function ( a, b ) {
  return a - b;
 },
 compute: function ( a, b ) {
  var sum = this.add( a, b );
  var difference = this.subtract( a, b );
  var total = sum + difference;

  return total;
 }
}

calculator.compute( 2, 3 ); //returns 4
sjmartin
  • 3,662
  • 4
  • 15
  • 31
  • 3
    [This MDN topic](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) should answer all of your questions. – Marty Mar 04 '16 at 00:21
  • Example 1: Yes; Example 2: Yes; Example 3: It's an object literal and you assign functions to its properties. There is no special term for that. – Felix Kling Mar 04 '16 at 00:25
  • 1
    Which method is "better" depends on context, and even then it's a matter of opinion. If you intend the functions to be available globally then the last method is my preference because it creates only one global variable. If the functions are local (that is, defined inside some other function) then I prefer the first way - unless they need to be defined conditionally for some reason, in which case I'd go with option two. (Clear? ;)) – nnnnnn Mar 04 '16 at 00:37
  • Thank you @Marty and Meiko. Both of these resources are great. I've read through them and while they explain what they are, I still cannot determine when I should use the functional declaration style over object literal style. It seems that I always see a lot of object literal styles more commonly. – sjmartin Mar 04 '16 at 00:38
  • 1
    The third style isn't necessarily more popular, you'll just see it more often because it's more logical to attach functions to objects that they interact with or could be grouped logically under e.g. putting mathematical functions into a `Math` object or putting functions like `getAge` and `getWeight` into a `Person` object. – Marty Mar 04 '16 at 00:40
  • Thank you @nnnnnn. I can understand what you mean by object literal only creating 1 global variable. But I don't understand the function within a function. Would that look something like: function calculator( function add(){...} subtract(){...} compute(){...})? – sjmartin Mar 04 '16 at 00:41
  • Yes, it would look something like that. Note that those inner functions are not visible to other code outside the containing function, they'd need to be called by code inside the same containing function. – nnnnnn Mar 04 '16 at 00:46
  • @nnnnnn fantastic thank you. I guess I never thought about declaring functions within functions before. I will need to investigate that further on my own. I really appreciate your help as well as everyone else! – sjmartin Mar 04 '16 at 00:47
  • "Nested functions" is the usual term for that, in case that helps you find more info. – nnnnnn Mar 04 '16 at 00:55
  • This question has [*many, many duplicates*](http://stackoverflow.com/search?q=%5Bjavascript%5D+function+declaration+vs+function+expression). – RobG Mar 04 '16 at 00:56
  • @Meiko—please do not reference w3schools, it's full of errors. Use either ECMA-262 or MDN, whichever seems appropriate. – RobG Mar 04 '16 at 00:57
  • Thanks @RobG, I did search and see those, but I was also looking for what I now know is called the "object method'' style. At the time I didn't know what it was called and was difficult to search for. – sjmartin Mar 04 '16 at 00:58

2 Answers2

3

is this called function declaration?

function add( a, b ) {
  return a + b;
}

Yes.

is this called function expressions?

var add = function ( a, b ) {
  return a + b;
};

Yes. Notice that only the function(…){…} part is the function expression, the rest is a normal assignment (variable declaration with initialiser, to be pedantic).

what is this method called?

… {
    add: function ( a, b ) {
        return a + b;
    },
    …
}

Again, it's a function expression. Used as a property value in an object literal here, to define a method.

Are any one of these methods better than the other?

Function declarations are preferred over assigning function expressions to variables (there are slight differences). You should use expressions only where you need them as an expression (e.g. in IIFEs, conditional assignments, property assignments, property definitions, return statements etc).

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
1

Function declaration:

function add(a,b) { return a+b; }

A function declaration is defined at parse time for a certain script block. It can be called anywhere in the block without producing an error:

(function() {
    add(3,3)    //The function block has already been parsed, add() is available
    function add(a,b) { return a+b; }
})();

Function expressions:

var add = function(a,b) { return a+b; }

Function expressions assign a variable to an anonymous function. These are evaluated at run time and cannot be called before being declared.

(function() {
    add(3,3)    //Error: add() has not yet been defined.
    var add = function(a,b) { return a+b; }
})();

Object Methods:

Methods, are functions that are a property of an object.

var obj = {
    propert1: 'property1 value',
    add: function(a,b) {
       return a+b;
    }
};

These may be called via obj.add(3,3), however not prior to declaring the object via an object literal or assignment of a method to a property.

Is there a preffered way?

Declaring functions via a function declaration offers flexibility. It may however lead to unexpected results, For example(raised functions):

(function returnVal() {
    function getSomething() {
        return 'foo';
    }
    return getSomething();

    function getSomething() {
        return 'bar';
    }
})();  //returns 'bar'

The return of the function may appear unexpected, however functions are raised during parse-time, and getSomething() is overridden.

Rewriting the code using a function expression produces the desired result

(function returnVal() {
    var getSomething = function() {
        return 'foo';
    }
    return getSomething();

    getSomething = function() {
        return 'bar';
    }
})(); //returns 'foo'

Object methods on the other hand act much like function expressions however they are accessible under the object's name.

var obj = {};
obj.foo = function() { /*code*/ }
obj.bar = function() { /*code*/ }

They act similarly to function expressions, however this groups code under the ownership of obj. For clarity you may wish to choose this.

Max
  • 2,258
  • 1
  • 17
  • 31
  • I hardly would call anything "expected" or "unexpectd" if you're declaring two functions with the same name :-) It's not an issue unless you're doing weird things. – Bergi Mar 04 '16 at 00:50
  • Man, this whole community is amazing. Learning so much. Thank you both Max and @Bergi for your responses and help. I've taken away a lot from your contributions! – sjmartin Mar 04 '16 at 00:52
  • No problem. You could look into [Function vs Function expression](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) for more in-depth differences between the two. Object methods act much like expressions. – Max Mar 04 '16 at 00:57
  • Regarding function expressions and "*These are parsed at run time…*", function expressions are parsed when all other code is parsed. What you probably meant is they are *evaluated* at run time. ;-) – RobG Mar 04 '16 at 01:04
  • "Error: add() has not yet been declared." --- it was declared, but was not defined. – zerkms Mar 04 '16 at 01:10