Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to use the Javascript arrow function?

Javascript Arrow function

The ES6 has introduced Javascript arrow functions, it provides a cleaner syntax for declaring an anonymous function, by dropping the function keyword and return key, when the function body only has one expression.

Advantages of Javascript Arrow function

  1. Arrow function are neat, clear and shorter as compare to traditional function expression.
  2. Arrow function provide concise syntax for writing function, is alternative to traditional function expression.
  3. Provide implicit returns, which allows us to write these nifty one-liners without need of return keyword.

Javascript arrow function syntax

The arrow function has a couple of different syntaxes depending on the number of arguments or the number of expressions in the function body.

Traditional method have return values as

let sum = function(x, y) {
    return x + y;
}

Arrow function without return keyword
let sum = (x, y) => x+y;
const sayHello = () => alert('Hello World');
Note: The => symbol is often referred to as the fat arrow symbol. Arrow function syntax are written general like this
param => statements/expression
Javascript arrow function syntax

Comparing arrow function with a traditional function expression

Arrow function is clean and is extremely concise for writing anonymous function as compared to traditional function. Let’s compare each other.

// Traditional function
function findLargestNum(num1, num2) {
   return (num1 > num2) ? num1 : num2;
}

findLargestNum(20, 30); //Output 30

//Arrow Function
findLargestNum = (num1, num2) => (num1 > num2) ? num1 : num2;

findLargestNum(20, 30);

square = (a) => a * a;

add = (a) => a + 100;

Note: Where findLargest is name of function and (num1 and num2) is parameter of function

Arrow functionRegular Function
An arrow function doesn’t have its own keyword and simply inherits this object from its parent instead of binding its own, so we don’t need to specify the binding of this keyword.In a regular function value of this is dependent on how a function is invoked and is always dynamic. For example in a simple function value of this is always referred to as a global window object, which returns undefined. But in the case of an object which invokes a method, the value of this is refer to the object itself.
Arrow function can’t be applied function constructor, using it will generate an error.We can easily apply a new keyword to make a constructor object from a function.
No need to add a return on the arrow function containing a single expression, as a return is implicit.Need to add a return function, if we want to return a value from the function.

Javascript Arrow function example

Now we had learned about the arrow function and its syntax. Let’s demonstrate a few examples of it. In our first example of an arrow function with one parameter, if we had one parameter in the arrow function then is optional to have parentheses. Let’s demonstrate the square of a number.

Arrow function with a single parameter and without parentheses

<!DOCTYPE html>
<html>
<body>
  <h4>Arrow Function syntax</h4>
  <p>Square of 4: <span id="squareID"></span></p>

  <script>
    const squareNum = num => num * num;

    document.getElementById("squareID").innerHTML = squareNum(4);
  </script>
</body>
</html>

In the above example, we call squareNum function with one argument, and for an argument no need for parentheses. Where squareNum arrow function will return the square of 4 is 16.

Arrow function with no parameter

In our Javascript arrow function example without any parameter. Click on the Hi hello button will call the alert function.

<!DOCTYPE html>
<html>
<body>
  <h4>Arrow Function syntax</h4>
  <p>Arrow function without parameter</p>
  <button id="btn">Hi hello</button>

  <script>
    const hiWorld = () => alert('Hello world !');

    document.getElementById("btn").addEventListener("click", () => {
      hiWorld();
    });
  </script>
</body>
</html>

Arrow function with multiple parameters

We can send multiple parameters to the arrow function and if we had more than one expression then we have to add a curly brace in an arrow function. Here is Javascript arrow function example with multiple parameters.

Example 1
equalCheck = (num1, num2) => (num1 === num2) ? true : false;
equalCheck(20, 30) // false
equalCheck(20, 20) // true


const message = (name, message, year) => {
  return `${ name }, ${message} ${year} from Edupala`;
};

message('Keanu', 'Happy new year', 2022);

Note: If we use the curly brace in the arrow function, then we need to add the return keyword before what value we want to return.

Arrow function features

  1. This scope with arrow function is inherited from the context and it doesn’t have its own this.
  2. The arrow function can’t be used as a constructor.
  3. It doesn’t have a prototype property.
  4. It can not use as a generator because they don’t allow the yield keyword.

Common use case of Javascript Arrow Function

The arrow function is not suitable for all situations. It is common and easy to use in array manipulation like a filter, map, reduce, and more. Some examples of map and filter usage. It is commonly used in the promise and observable.

const students = [
   { name: 'Alex', age: 25 },
   { name: 'Caroline', age: 23 },
   { name: 'John', age: 30 },
   { name: 'John', age: 26 },
];

const ages = students.map((student) => student.age);
console.log(ages); // [25,23,30,26]

const studentAbove25 = students.filter((student) => student.age > 25);
console.log(studentAbove25); 
// [{name: 'John', age: 30}, {name: 'John', age: 26}]

Arrow function return types

Like any other function in Javascript can return any data type, in the above example equalCheck we return a boolean value, in the map example, we return a number, and in filter object arrays. Let’s use the Arrow function to return an object,

const courseDetails = (name, year, duration) => ({ name, year, duration});
console.log(courseDetails('Ionic basic', '2021 - 22', '2 Hrs'));

// Output : 
{ name: 'Ionic basic', year: '2021 - 22', duration: '2 Hrs'}

In the arrow function, we don’t need to add name: name like this, as both have the same name, adding parameters with the same name is the same name only.

When not to use Arrow Function

Arrow function is flexible and provides us with clean code, but it is not suitable for all situations. As we know the arrow function doesn’t have its own this keyword, which is not suitable to use for object methods and constructors.

const student = {
  name: 'Edupala',
  course: 'Computer Science',
  year: 2021,
  studentMethod: function() {
    console.log(`Student name: ${ this.name }  
                 Course: ${ this.course } at ${ this.year }`)
  },
  
  anonymousMethod: () => { // Arrow function
    console.log(`Student name : ${ this.name } at ${ this.course}`);
  }
}

student.studentMethod();
Output: Student name: Edupala Course: Computer Science at 2021

student.anonymousMethod();
Output : Student name : undefined at undefined

In object student, we can see that the studentMethod function works perfectly with this keyword and we can access object properties inside the regular function.

Warning But this is not in the case of the arrow function, we can’t use this keyword in the arrow function as it shows undefined.

Javascript Arrow function with async

The arrow function is extensively used with map, filter, forEach, and many more. We can use the arrow function with async, special we used with promise and observable.

Arrow function with async example

The arrow function is anonymous and doesn’t have its own this scope. Hence, this is of the current context.

Conclusion
Arrow functions have pros and cons, it is suitable to use with inline functions, as parameters or callbacks, and use regular functions when working with object methods or constructors, due to how this works.

Related posts

How to use the Javascript arrow function?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top