
Arrow Functions
An arrow function is the updated syntax to the regular function syntax. The update was made when ES6 was released. The syntax is supposed to save time and simplify function scope. Arrow functions do not have their own bound this, arguments, super and new.target. They are not good for writing methods and cannot be used as constructors.
//regular syntax
function foo(){
return 'bar';
}
//arrow syntax
const bar = () => {
return 'foo';
};
If there is only one parameter being passed to the function you can drop the curly braces and the parentheses. With this "concise" syntax the return statement is implied. If you have multiple parameters you cannot drop either.
//one parameter
const data = (num) => num * num;
/*or*/
const total = num => num * num;
//multiple parameters
const foo = (a,b) => { return a/b };
Arrow functions can also return object literals like regular functions.
const student = (name, grade) => ({name: name, grade: grade });
console.log(student('Courtney','Senior'));
//{name: "Courtney", grade: "Senior"}
//When the parameters have the same name as the object keys
//you can rewrite like this
const student2 = (name, grade) => ({name, grade });
student2('stu','freshman')
//{name: "stu", grade: "freshman"}
Common uses of arrow functions include array manipulation, promise chains, and functions that don't have parameters such as setTimeout.
/*Array Manipulation*/
const prices = [10,4,7,22,6,79];
prices.map(p => p * 2);
//[20, 8, 14, 44, 12, 158]
const grades = [77, 62, 90, 87];
grades.filter(g => g > 70);
//[77, 90, 87]
/*Parameter less arrow functions*/
setTimeout(() => {
console.log('Hi');
}, 500);
/*Promise Chaining*/
promise
.then(() => promise2())
.then(() => promise3)
.done(() => console.log('finished'));
As I stated in the intro, arrow functions do not have a bound this, arguments, super, and new.target. Meaning they will always be inherited from the enclosing scope.
//this
const hi = {
id: 2,
getID: () => {
console.log(this.id, this); //undefined, window
},
fun: function(){
console.log(this.id, this);// 2, {id: 2, getID: ƒ, fun: ƒ}
}
};
//arguments
let nums = [1,2,3,4,5];
const data = function(n,x,y){console.log(arguments)};
data(nums, 'hello', 'x');
//Arguments(3)[Array(5), "hello", "x", callee: ƒ, Symbol(Symbol.iterator): ƒ]
const info = (nums) => console.log(arguments);
info(nums);
//Uncaught ReferenceError: arguments is not defined
//prototyping
function talk(words) {
console.log(words);
}
console.log(talk.hasOwnProperty('prototype'));//true
const talk2 = words => console.log(words);
console.log(talk2.hasOwnProperty('prototype'));//false
For a deep dive into arrow functions click here.