Функция стрелки JavaScript
hello = () => {
return "Hello World!";
}
Ankur
hello = () => {
return "Hello World!";
}
let numbers = (x, y, z) => (x + y + z) * 2;
console.log(numbers(3, 5, 9))
//Expected output:34
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
// Arrow Functions Shorthand javascript
// Longhand:
function sayHello(name) {
console.log('Hello', name);
}
sayHello("Chetan"); // Hello Chetan
setTimeout(function() {
console.log('Loaded'); //Loaded
}, 2000);
[1,2,3].forEach(function(item) {
console.log(item);
// 1
// 2
// 3
});
// Shorthand:
sayHello = name => console.log('Hello', name);
sayHello("Chetan"); //Hello Chetan
setTimeout(() => console.log('Loaded'), 2000); //Loaded
[1,2,3].forEach(item => console.log(item));
// 1
// 2
// 3
// An empty arrow function returns undefined
let empty = () => {};
(() => 'foobar')();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)
var simple = a => a > 15 ? 15 : a;
simple(16); // 15
simple(10); // 10
let max = (a, b) => a > b ? a : b;
// Easy array filtering, mapping, ...
var arr = [5, 6, 13, 0, 1, 18, 23];
var sum = arr.reduce((a, b) => a + b);
// 66
var even = arr.filter(v => v % 2 == 0);
// [6, 0, 18]
var double = arr.map(v => v * 2);
// [10, 12, 26, 0, 2, 36, 46]
// More concise promise chains
promise.then(a => {
// ...
}).then(b => {
// ...
});
// Parameterless arrow functions that are visually easier to parse
setTimeout( () => {
console.log('I happen sooner');
setTimeout( () => {
// deeper code
console.log('I happen later');
}, 1);
}, 1);