DEV Community

Cover image for Javascript Arrow Function
Let's Code
Let's Code

Posted on • Updated on

Javascript Arrow Function

Javascript Arrow is an alternative syntax to the old regular function.

There is two main use case of using a javascript arrow function. The first is that it makes the code shorter and concise like below.

No argument
// Regular Function
function sayHello() {
  return 'Hello'
}

// Arrow Function
const sayHello = () => 'Hello'
Enter fullscreen mode Exit fullscreen mode
One argument
// Regular Function
function addTen(number) {
  return number + 10
}

// Arrow Function
// Notice that we can remove the parenthesis around the parameter when argument is just one. It is optional.
const addTen = num => number + 10 
Enter fullscreen mode Exit fullscreen mode
Two or more arguments with multiple function body statements. We have to keep the curly braces and the return keyword for multiple function body statements.
// Regular Function
function addTen(number1, number2) {
  const ten = 10                   // function body line #1
  return number1 + number2 + 10    // function body line #2
}

// Arrow Function
const addTen = (number1, number2) => {
  const ten = 10
  return number1 + number2 + 10
}
Enter fullscreen mode Exit fullscreen mode

The second use case of the arrow function is to handle the scope better. Let see a very simple example.

const person = {
    myName: John Doe,
    sayName () {
        setTimeout(function() {
             console.log(`Hi, ${this.myName}`)
        }, 1000)
    }
}
Enter fullscreen mode Exit fullscreen mode

When we invoke

person.sayName() 
Enter fullscreen mode Exit fullscreen mode

We expect to see

Hi, John Doe
Enter fullscreen mode Exit fullscreen mode

Unfortunately, will get below.
It is because the function is pointing to the window object and window object doesn't have a method called sayName.

Hi, undefined
Enter fullscreen mode Exit fullscreen mode

To fix the context issue, engineers use these workarounds

Fix #1:

// Save the context and use that context
const person = {
    myName: John Doe,
    sayName () {
        const _this = this
        setTimeout(function() {
             console.log(`Hi, ${_this.myName}`)
        }, 1000)
    } 
}
Enter fullscreen mode Exit fullscreen mode

Fix #2:

// Use bind to ensure that context is set and kept
const person = {
    myName: John Doe,
    sayName () {
        setTimeout(function() {
             console.log(`Hi, ${this.myName}`)
        }.bind(this), 1000)
    } 
}
Enter fullscreen mode Exit fullscreen mode

Fix #3 - Modern solution

Arrow function behaves like a variable, it establishes the value of this (context) where the arrow function is created

// Using Arrow Function. 
const person = {
    myName: John Doe,
    sayName () {
        setTimeout(() => console.log(`Hi, ${this.myName}`), 1000)
    } 
}
Enter fullscreen mode Exit fullscreen mode

If you prefer to watch a 5 minutes video instead, below is the link

If you want to support me - Buy Me A Coffee

Top comments (1)

Collapse
 
peerreynders profile image
Info Comment hidden by post author - thread only accessible via permalink
// function declaration
function sayHello() {
  return 'Hello'
}

// function expression
const sayHello2 = function() {
  return 'Hello'
};

// arrow function expression
const sayHello3 = () => 'Hello';
Enter fullscreen mode Exit fullscreen mode

Function declarations are hoisted while function expressions are not.

// Using a closure
function makePerson(myName) {
  const greet = () => console.log(`Hi, I'm ${myName}`);
  return {
    myName,
    sayName() {
      setTimeout(greet, 1000);
    },
  };
}

const person = makePerson('John Doe');
Enter fullscreen mode Exit fullscreen mode
// constructor function
function Person(myName) {
  const greeting = `Hi, I'm ${myName}`;
  this.greet = () => console.log(greeting);
  this.myName = name;
}

Person.prototype.sayName = function () {
  setTimeout(this.greet, 1000);
};

const person = new Person('John Doe');
Enter fullscreen mode Exit fullscreen mode

Some comments have been hidden by the post's author - find out more