Why do Arrow functions exist and how could you use them in objects if you wanted to?



If arrow functions do not depend on where the function is called, why do they exist and how could you use them in objects if you wanted to?


Arrow functions have been adopted by JavaScript to provide an easier, shorter syntax, and a clearer definition of the keyword this which will always be bound to the enclosing lexical context (aka the global scope where it exists). An example of how they provide an easier syntax would be:

//As a callback

const duplicates = [1,2,3,4].map(num =>  num * 2 );

There, we can see that an arrow function as a one-liner does not need curly braces, parenthesis around the parameter, or a return keyword. In that form, they all become optional. When we have to provide two or more arguments, we need to have parenthesis, and when we need more than one line of operations in the function, we need curly braces and the return keyword. Ie.:

const duplicatePairs = [1,2,3,4].map((num, index) =>  {
  let newNum = num*2;
  const pair = {};

  pair[index] = newNum;

  return pair;
  } )

console.log(duplicatePairs) //[ { 0: 2 }, { 1: 4 }, { 2: 6 }, { 3: 8 } ]

It is not recommended to use arrow functions in objects for the limiting use of the keyword this, yet if we really wanted to write an arrow function in an object and we wanted to refer to the calling object, we have to make a direct reference by using the object’s name. Ie.:

const robot = {
  energyLevel: 100,
  checkEnergy: () => {
    console.log(`Energy is currently at ${robot.energyLevel}%.`)

robot.checkEnergy(); //Energy is currently at 100%.

const newRobot = robot; //to demonstrate that referring to robot in the main 
                        //object, but that it becomes an inherent value that
                        //that refers back to the object.
newRobot.energyLevel = 50;
newRobot.checkEnergy() // Energy is currently at 50%.
robot.checkEnergy() // Energy is currently at 50%.

Again, this is a case where we could say an arrow function might not be as efficient as a method.