Arrow Functions

  • Created using arrow operator
  • Arrow functions do not have this and arguments object in current lexical environment. In other words it picks up these objects from the outer lexical environment since inner lexical environment does not have them.
  • Since this is not available, we cannot call new and use arrow functions as constructor.
const Person = () => {
    this.name = 'KK';
}
 
var person = new Person(); // TypeError: Person is not a constructor
  • Uses: They do not have context and usually used where short pieces of code needs to be executed in the current context
const group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],
 
  showList() {
    this.students.forEach(function(student) {
      // Error: Cannot read property 'title' of undefined
      alert(this.title + ': ' + student);
    });
 
	this.students.forEach((students) => {
		// works
		alert(this.title + ': ' + student);
	})
  }
};
 
group.showList();