<commit_before>---
layout:     post
title:      "Service vs Factory - Once and for all"
imageUrl: "/images/banner/service-vs-factory.png"
relatedLinks:
  -
    title: "Using ES6 with Angular today"
    url: "http://blog.thoughtram.io/angularjs/es6/2015/01/23/exploring-angular-1.3-using-es6.html"
date:       2015-07-07
update_date: 2015-07-07
summary:    "This is yet another article on services vs factories in AngularJS. It explains once and for all, why we mostly want to use service."

categories: 
  - angular

tags:
  - angular

author: pascal_precht
---

Wait, what? Yet another article that answers the big question: Service vs Factory, what should I use? Yes, it seems that this is not needed anymore, since there are a ton of resources in the internet that discuss that topic. It turns out that this question still pops up every week or so on different channels, and even after reading the top ten answers on StackOverflow, it's still not very clear. Despite that, it also appears that the current resources on the web don't really promote the actual best practice, especially if we consider the recent movements of the web platform. ES6 I'm looking at you!

This article explains once and for all the difference between services and factories and why **we want to prefer services over factories**.


## The difference between services and factories

Okay, so what is the difference between a service and a factory in AngularJS? As we all know, we can define a service like this:

{% highlight javascript %}
{% raw %}
app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});
{% endraw %}
{% endhighlight %}

`.service()` is a method on our module that takes a name and a function that defines the service. Pretty straight forward. Once defined, we can inject and use that particular service in other components, like controllers, directives and filters, like this:

{% highlight javascript %}
{% raw %}
app.controller('AppController', function (MyService) {
  MyService.sayHello(); // logs 'hello'
});
{% endraw %}
{% endhighlight %}

Okay, clear. Now the same thing as a factory:

{% highlight javascript %}
{% raw %}
app.factory('MyService', function () {
  return {
    sayHello: function () {
      console.log('hello');
    };
  }
});
{% endraw %}
{% endhighlight %}

Again, `.factory()` is a method on our module and it also takes a name and a function, that defines the factory. We can inject and use that thing exactly the same way we did with the service. Now what is the difference here?

Well, you might see that instead of working with `this` in the factory, we're returning an object literal. Why is that? It turns out, **a service is a constructor function** whereas a factory is not. Somewhere deep inside of this Angular world, there's this code that calls `Object.create()` with the service constructor function, when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object explicitly.

To make that a bit more clear, we can simply take a look at the Angular source code. Here's what the `factory()` function looks like:

{% highlight javascript %}<commit_msg>Removed a Semicolon (#117)<commit_after>---
layout:     post
title:      "Service vs Factory - Once and for all"
imageUrl: "/images/banner/service-vs-factory.png"
relatedLinks:
  -
    title: "Using ES6 with Angular today"
    url: "http://blog.thoughtram.io/angularjs/es6/2015/01/23/exploring-angular-1.3-using-es6.html"
date:       2015-07-07
update_date: 2015-07-07
summary:    "This is yet another article on services vs factories in AngularJS. It explains once and for all, why we mostly want to use service."

categories: 
  - angular

tags:
  - angular

author: pascal_precht
---

Wait, what? Yet another article that answers the big question: Service vs Factory, what should I use? Yes, it seems that this is not needed anymore, since there are a ton of resources in the internet that discuss that topic. It turns out that this question still pops up every week or so on different channels, and even after reading the top ten answers on StackOverflow, it's still not very clear. Despite that, it also appears that the current resources on the web don't really promote the actual best practice, especially if we consider the recent movements of the web platform. ES6 I'm looking at you!

This article explains once and for all the difference between services and factories and why **we want to prefer services over factories**.


## The difference between services and factories

Okay, so what is the difference between a service and a factory in AngularJS? As we all know, we can define a service like this:

{% highlight javascript %}
{% raw %}
app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});
{% endraw %}
{% endhighlight %}

`.service()` is a method on our module that takes a name and a function that defines the service. Pretty straight forward. Once defined, we can inject and use that particular service in other components, like controllers, directives and filters, like this:

{% highlight javascript %}
{% raw %}
app.controller('AppController', function (MyService) {
  MyService.sayHello(); // logs 'hello'
});
{% endraw %}
{% endhighlight %}

Okay, clear. Now the same thing as a factory:

{% highlight javascript %}
{% raw %}
app.factory('MyService', function () {
  return {
    sayHello: function () {
      console.log('hello');
    }
  }
});
{% endraw %}
{% endhighlight %}

Again, `.factory()` is a method on our module and it also takes a name and a function, that defines the factory. We can inject and use that thing exactly the same way we did with the service. Now what is the difference here?

Well, you might see that instead of working with `this` in the factory, we're returning an object literal. Why is that? It turns out, **a service is a constructor function** whereas a factory is not. Somewhere deep inside of this Angular world, there's this code that calls `Object.create()` with the service constructor function, when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object explicitly.

To make that a bit more clear, we can simply take a look at the Angular source code. Here's what the `factory()` function looks like:

{% highlight javascript %}
{'fraction_non_alphanumeric': 0.08472998137802606, 'fraction_numerical': 0.009776536312849162, 'mean_word_length': 4.03515625, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2365594', 'n_tokens_mistral': 1784, 'n_tokens_neox': 1620, 'n_words': 897}