Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active August 25, 2018 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mojaray2k/8a58e14079bfc4ed421e55806996762a to your computer and use it in GitHub Desktop.
Save mojaray2k/8a58e14079bfc4ed421e55806996762a to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/diqumox
/* Fat Arrow Functions */
// arrow function example #1 - with implicit return
const add = (a, b) => a + b;
const sum = add(1,2)
console.log(sum);
// arrow function example #2 - if you only have one argument you don't need ()
const double = number => 2 * number;
const multiply = double(8);
console.log(multiply);
// arrow function example #3 - this is a compact funciton for methods
const numbers = [1,2,3,4];
const countNumbers = numbers.map(number => 2 * number);
console.log(countNumbers);
// arrow function example #4
// This is the ES5 way example 1
const Team1 = {
members: ['Jane', 'Bill'],
teamName: 'Super Squad 1',
teamSummary: function() {
return this.members.map(function(member) {
return `${member} is on team ${this.teamName}`;
}.bind(this))
}
}
const team1 = Team1.teamSummary();
console.log(team1);
// This is the ES5 way example 1
const Team2 = {
members: ['Jill', 'Gil'],
teamName: 'Super Squad 2',
teamSummary: function() {
var self = this;
return this.members.map(function(member) {
return `${member} is on team ${self.teamName}`;
})
}
}
const team2 = Team2.teamSummary();
console.log(team2);
// This is the ES6 way - Example 1 - using lexical this for the map function
const Team3 = {
members: ['Suzy', 'Sam'],
teamName: 'Super Squad 3',
teamSummary: function() {
// this === team
// team.teamName in the anonymous function that map uses is the same as this.teamName
return this.members.map((member) => {
return `${member} is on team ${this.teamName}`;
})
}
}
const team3 = Team3.teamSummary();
console.log(team3);
// This is the ES6 way - Example 2 - when not to use arrow functions with this
const Profile = {
name: 'Alex',
getName: function(){ return this.name }
}
const profile = Profile.getName();
console.log(profile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment