PacketSniffer
PacketSniffer

Reputation: 127

Why are Javascript Functions declared in different ways

Apologies if this seems like a beginner question, I am currently learning Javascript and have come across different ways of structuring function declarations. An example below

function mapStateToProps(state) {
    console.log(state);
}

const mapStateToProps = state => {
    console.log(state);
}

What is the benefit of using one or the other; in which situation would you use one over the other?

Upvotes: 0

Views: 86

Answers (2)

Daniel
Daniel

Reputation: 15413

The first example is a function declaration and the second example is a function expression. The second example you provided only serves to provide more concise JavaScript code to the first example and doesn't really capture the idea of your question of when to use ES6 arrow functions over function declarations. In other words your example, is just syntactic sugar, in your examples, nothing is really solved, just more concise code.

A better example is the following:

const team = {
	members: ['Dolly', 'Billy'],
  teamName: 'Hacking Crew',
  teamSummary: function() {
  	return this.members.map(function(member) {
    	return `${member} is on team ${this.teamName}`;
    });
  }
};

console.log(team.teamSummary());

Run this snippet and you will see the error. Now, this error does not have to be solved with the arrow function, there are a couple of ways to solve it, but your question of in which situation would you use one over the other, this is a good use case for using an arrow function to solve this error.

Before I provide the solution, understand that fat arrow functions make use of what is called the lexical this. I will provide the refactor below and then unpack my previous sentence:

const team = {
	members: ['Dolly', 'Billy'],
  teamName: 'Hacking Crew',
  teamSummary: function() {
  	return this.members.map((member) => {
    	return `${member} is on team ${this.teamName}`;
    });
  }
};

console.log(team.teamSummary());

Lexical means the placement of this term depends on how its interpreted or how its evaluated. So, depending on where we are placing the word this will change when using a fat arrow function.

When we use a fat arrow function and make reference to this inside of it this is automatically set equal to this in the surrounding context which in this code snippet is the team object.

So if lieu of using .bind(this) and having to cache a reference to this, you can replace fat arrow function as a solution.

Upvotes: 0

Alexandr Dobrovolsky
Alexandr Dobrovolsky

Reputation: 66

Arrow functions are the new ES2015 syntax, for me the main difference is changing this context you may read about it here https://medium.com/@thejasonfile/es5-functions-vs-es6-fat-arrow-functions-864033baa1a

Upvotes: 1

Related Questions