## 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");
}
// 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");
}
Num | Topic |
---|---|
2.2.1 | The New Token (fat arrow) |
2.2.2 | New ways to declare a function |
=>
function (arguments){ expression }
arguments => expression
Kind of what we are really doing is removing and "improving" the syntax
- 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…}
var ES5foo1 = function(){ return 1; };
var ES6foo2 = () => 1;
// 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'));
// 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 });
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
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
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
var arr = ['a', 'e', 'i', 'o', 'u'];
arr.forEach(vowel => {
console.log(vowel);
});
setTimeout(function(){
console.log('ES5 2 sec');
}, 2000);
setTimeout(()=>{console.log('ES6 3 sec');}, 3000);
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
let test = name => `Introduction to ${name}!`;
console.log(test('ES6 JS Arrow Functions'));
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'));
// ES6
var sayHello = (msn, n) => msn + ' ' + n;
console.log(sayHello('Hi','there'));
setTimeout(() => { console.log('Hello'); }, 2000);
let square = num => num * num;
console.log( square(10) );
// 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);
A better way to declare a loop Array
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
}
var arr = [1,2,3,4,5,6,7,8];
var i=0, length = arr.length;
while (i<length){
console.log(arr[i]);
i++;
}
var arr = [1,2,3,4,5,6,7,8];
arr.forEach(function(i){
console.log(i);
});
let arr = [1,2,3,4,5,6,7,8];
arr.forEach(i => console.log(i));
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')
});
}
(function (n) {
return x;
})();
((n) => x)()