Skip to content

Latest commit

 

History

History
144 lines (83 loc) · 2.23 KB

Arrows Functions.md

File metadata and controls

144 lines (83 loc) · 2.23 KB

Arrows

Arrows => are function shorthand.

Table of Contents

  1. IIFE
  2. Function Expression
  3. this

IIFE

Immediately invoked function expression (iife).

Demo

In ES6

() => { alert('Hello World!') }()

or 

(() => 7)()

Converts into vanilla js as below

'use strict';

(function () {
  alert('Hello World!');
})();

or

(function () {
  return 7;
})();

You might have noticed use strict in coversion. ES6 transpilers adds it by default. But for upcoming examples I am going to simply ignore use strict

Function Expression

Demo

var funz = () => someStatement

// equivalent to: => { return someExpression }

Converts into vanilla js as below

var funz = function funz() {
  return someStatement;
};

⬆ back to top

this

the value of this is undefined in use strict mode function calls

Example in vanilla js

Demo

'use strict';

function father(){
  this.age = 0;

  function son() {
    console.log(this.age); //print undefined
  }
  
  son();
}

var f = new father();

>In ES6, Arrows bind `this` to immediate enclosing lexical scope. You don't have to use `bind()` or `var that = this;` to bind `this` anymore.
In ES6

Demo

function father() {
  this.age = 0;
  
  () => {console.log(this.age)}()
}

var f = new father();

Converts into vanilla js as below

function father() {
  var _this = this;

  this.age = 0;

  (function () {
    console.log(_this.age); //print 0
  })();
}

var f = new father();

⬆ back to top

Reference