When should you use arrow functions?

by Génesis García Morilla

JavaScript

(function() {
  console.log(this); // this = Window
})(); 
(() => console.log(this))(); // this = window

// Person Constructor
function Person(first, last) {
  this.first_name = first;
  this.last_name = last;
}

// New method for Person
Person.prototype.name = function() {
  return this.first_name + ' ' + this.last_name; // this = Person
};

// Never use arrow functions when adding method
Person.prototype.name2 = () => this.first_name + " " + this.last_name; // this = Window

// However, you should use it if you want to preserve the context inside
Person.prototype.career = function(array) {
  // this = Person
  return array.map(function(a) {
    return this.first_name + ' ' + a; // this = Window
  });
};

Person.prototype.career2 = function(array) {
  return array.map(a => this.first_name + ' worked at ' + a); // this = Person
};

// Open the console to see the results
var ed = new Person('Edward', 'Snowden');
console.log(ed.name());
console.log(ed.name2());
console.log(ed.career(['CIA', 'NSA']));
console.log(ed.career2(['CIA', 'NSA']));