Arrow Functions

Also known as the Fat Arrow.
Array functions are anonymous and change the way 'this' binds in functions.
These can be used to simplify function scoping.
A function can be re-written using the fat arrow.
By using the Fat Arrow we do not have to type the 'function' keyword, type the return keyword
Curly brackets are also not required if the function only contains one expression.


When you use a Regular function (with the function keyword), the value of the 'this' keyword depends on HOW the function was called (the object that made the call)

const myFunc1 = function () { 
};

is equivalent to this

const myFunc2 = () => { 
};

When you use an Arrow function, the value of the 'this' keyword depends on WHERE the function was defined (the scope where the function was defined)
Arrow functions are extremely useful when working with Events and Listeners.
Regular functions provide access to their "calling" environment while arrow functions provide access to their "defining" environment.



A function expression is an anonymous function object that we set equal to a variable


This is defined using a pair of parenthesis that contain the list of parameters followed by a fat arrow and a pair of curly brackets

var checkNum = (num) => { 
   return num % 2 === 0;
}


Functions - No Parameters

const returnfifty_var = function() { 
   return 50;
};

const returnfifty_var = () => { return 50; }
const returnfifty_var = () => 50;


Functions - One Parameter

const addfifty_var = function(x) { 
   return x + 50;
};

const addfifty_var = (x) => { return x + 50; }
const addfifty_var = (x) => x + 50;


Functions - Multiple Parameters

const addtwonumbers_var = function(x, y) { 
   return x + y;
};

const addtwonumbers_var = (x, y) => { return x + y; }
const addtwonumbers_var = (x, y) => x + y;


let age = prompt("What is your age?", 18); 

let welcome = (age < 18) ?
  () => alert('Hello') :
  () => alert("Greetings!");

welcome(); // ok now


© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext