Arrow functions

They can’t be use with new because of how they bind this.

  1. var fn1 = function() {return 2;};
  2. var fn2 = () => 2; // Here you can omit curly braces. It means return 2. If you add curly braces then you have to put the word 'return'.

Parenthesis-Parameter Rules

  1. var x;
  2. x = () => {}; // No parameters, MUST HAVE PARENS
  3. x = (val) => {}; // One parameter w/ parens, OPTIONAL
  4. x = val => {}; // One parameter w/o parens, OPTIONAL
  5. x = (y, z) => {}; // Two or more parameters, MUST HAVE PARENS
  6. x = y, z => {}; // Syntax Error: must wrap with parens when using multiple params

REAL benefit: lexical binding of ‘this’

You don’t need to bind(this) or var _this = this.

  1. var widget = {
  2. init: function() {
  3. document.addEventListener("click", (event) => {
  4. this.doSomething(event.type);
  5. }, false);
  6. },
  7. doSomething: function(type) {
  8. console.log("Handling " + type + " event");
  9. }
  10. };
  11. Widget.init();

You can’t replace all functions with Arrow functions because it will mess up this.

Auto call

  1. (() => "foobar")() // returns "foobar"