Skip to content

Latest commit

 

History

History
409 lines (324 loc) · 7.94 KB

2.2-Arrow functions.md

File metadata and controls

409 lines (324 loc) · 7.94 KB

## 2.2-Arrow functions: => ecma-international.org

The REAL benefit: lexical binding of 'this': Provide a work around to: ‘that = this’ or ‘bind()’, with a more compact version of an ‘anonymous function syntax’.

Function Statement are declared in the same way as ES5 (because they will remain anonimous)

hoisted(); // logs "foo" 
function hoisted() { 
  console.log("foo"); 
}

check HOW this remain anonimous

// ES6
()=>{};

// will compile
(function () {});

// or
(() => "foobar")()

// will compile
(function () {
  return "foobar";
})();

Function Expressions CHANGE here

// ES5
notHoisted(); // TypeError: notHoisted is not a function 
var notHoisted = function() { 
  console.log("bar"); 
};

and provide a shorted manner

// ES6
let notHoisted=()=>{
  console.log("bar"); 
}

Table of contents

Num Topic
2.2.1 The New Token (fat arrow)
2.2.2 New ways to declare a function

Never type the word "function" ever again.

The New Token (fat arrow)

=>

The old ES5 syntax

function (arguments){ expression }

The new ES6 Syntax

arguments => expression

Kind of what we are really doing is removing and "improving" the syntax

Scope with var and let

  • Fat arrows change how this is handled.
  • ES6 Arrows bind this to the immediate enclosing lexical scope
<ul>
  <li>foo</li>
  <li>bar</li>
</ul>
<button id="b1">function</button>
<p>
<button id="b2">arrow function</button>

$("#b1").click(function () {
    $("li").each(function () {
        console.log(this);
    });
}); // <li>foo</li><li>bar</li>

$("#b2").click( ()=> {
    $("li").each( ()=> console.log(this) );
}); // Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}

Comparing ES5/ES6 functions

var ES5foo1 = function(){ return 1; };
var ES6foo2 = () => 1;

Example

Comparing ES5 functions and ES6 Arrow Functions

// ES5
var sayHello = function(msn, name){
    return msn + ' ' + name;
};
console.log(sayHello('Hi','there'));

// ES6
let sayHello = (msn, name) => {
    return msn + ' ' + name;
};
console.log(sayHello('Hi','there'));

Ej1: Arrow

Declaration statement variations

// single param => single statement
param => expression;

// multiple params => single statement
(param [, param]) => expression;

// single param, multiple statements
param => {
    statements;
}

// multiple params, multiple statements
([param] [, param]) => {
   statements
}

// with no params, single statement
() => expression;

// with no params, multiple statements
() => {
    statements;
}

// one statement, returning an object
([param]) => ({ key: value });

Parenthesis-Parameter Rules

let x;
x =   ()    => {};  // No parameters, MUST HAVE PARENS
x = (val)   => {};  // One parameter w/ parens, OPTIONAL
x =  val    => {};  // One parameter w/o parens, OPTIONAL
x = (x,y,z) => {};  // Two or more parameters, MUST HAVE PARENS

Parenthesis Rules scenarios ES5/ES6 comparison

function (n){}; //ES5

n =>{} //ES6
"use strict";       // ES5
var x = function(){};

x = () => {};       // ES6
"use strict";       // ES5
var x = function(val){};

x = (val) => {};    // ES6
"use strict";       // ES5
var x = function(val){};

x = val => {};      // ES6
"use strict";       // ES5
var x = function(x,y,z){};

x = (x,y,z) => {};  // ES6

Immediately-invoked function expression (IIFE) ON ES6

ECMAScript 5 does not have block-scoped variables. In order to simulate blocks, you use the IIFE

(function () {  // open IIFE
    var tmp = ...;
    ...
}());  // close IIFE

In ECMAScript 6, you can simply use a block + let variable declaration:

{  // open block
    let tmp = ...;
    ...
}  // close block

Using forEach

var arr = ['a', 'e', 'i', 'o', 'u'];
arr.forEach(vowel => {
    console.log(vowel);
});

forEach

Using setTimeout() on ES5 and ES6

setTimeout(function(){
  console.log('ES5 2 sec');
}, 2000);

setTimeout(()=>{console.log('ES6 3 sec');}, 3000);

setTimeout ES5

Return an object literal that's wrap in parentesis

let foo = val => ({key: val});
console.log(JSON.stringify( foo('Leo'))); 
```javascript
[object literal](http://www.es6fiddle.net/idre3j66/)


### No return required
> When using a single expression after the arrow, the return is implicit, there is no need for a return in the expression

```javascript
let foo1 = test => `The, ${test}!`;
let foo2 = test => { return `The, ${test}!` };
console.log(foo1('js') === foo2('js')); // true

return/No return

let test = name => `Introduction to ${name}!`;
console.log(test('ES6 JS Arrow Functions')); 

return/No return

const foo1 = name => `Introduction to ${name}!`;
console.log(foo1('ES6 JS Arrow Functions')); 

const foo2 = name => {
    let n = `Introduction to ${name}!`;
    return n;
};
console.log(foo2('ES6 JS Arrow Functions')); 

return/No return

// ES6
var sayHello = (msn, n) => msn + ' ' + n;
console.log(sayHello('Hi','there'));

Ej1 - short

setTimeout(() => { console.log('Hello'); }, 2000);  

Ej2: Example

let square = num => num * num;
console.log( square(10) );

Ej3: Example

New ways to declare a function:

// Function Declarations
function mul (x, y) {
  return x * y;
}
console.log(mul);
console.warn(typeof mul);

// Function Expressions
var div = function (x, y) {
  return x / y;
};
console.log(div);
console.warn(typeof div);

// Arrow functions
const add = (x, y) => {
  return x + y;
};
console.log(add);
console.warn(typeof add);

// New ways to declare function:

// Concise methods
const MathUtils = {
  add (x, y) {
    return x + y;
  }
};
console.log(MathUtils);
console.warn(typeof MathUtils);

// Classes
class Point {
  constructor (x, y) {
    this.x = x;
    this.y = y;
  }
}
console.log(Point);
console.warn(typeof Point);

Declaring a function:

Loop Array

A better way to declare a loop Array

On ES4.01 version

var arr = [1,2,3,4,5,6,7,8];
var i=0, length = arr.length;
for (i;i<length;i++){
  console.log(arr[i]); //1,2,3,4,5,6,7,8
}

for ES4.01 example

while ES4.01 version

var arr = [1,2,3,4,5,6,7,8];
var i=0, length = arr.length;
while (i<length){
  console.log(arr[i]);
  i++;
}

while example

Array.prototype.forEach ES5 version

var arr = [1,2,3,4,5,6,7,8];
arr.forEach(function(i){
  console.log(i);
});

forEach ES5 example

Array.prototype.forEach ES6 version

let arr = [1,2,3,4,5,6,7,8];
arr.forEach(i => console.log(i));

forEach ES6 example

Validate mandatory parameter ES6 version

function missingParams() {
    console.log('error on mandatory parameter')
}
    
function checkParams(incident = missingParams()) {
  myServiceUtil.getThosFromDatabase(incident).then( n => {
    console.log('return')
  }, error => {
    console.log('error on promise')
  });
}

IIFE ES5 to 6 version

(function (n) {
  return x;
})();
((n) => x)()