• Post category:JavaScript
  • Reading time:5 mins read

In this article, we will learn about JavaScript Arrow function. Arrow functions were introduced in ES6 / ECMAScript 2015 and provides a concise way to write functions in JavaScript.

Here We have provided the syntax difference between the Normal function and Arrow function.

Normal function
function calculate() {
  //...
}
Arrow function
const calculate = () => {
  //...
}

Way to write arrow functions in JavaScript

  1. No Parameters function
  2. Single Parameter function
  3. Multiple Parameter function
  4. Single line No Parameter function (Implicit return)
  5. Single line Single Parameter function (Implicit return)
  6. Single line Multiple Parameters function (Implicit return)

1. No Parameters function

If you don’t have any parameters in function and you want to use the arrow function then just use ().

let getDefaultValue = () => {
  ...
  return {
    number: 50,
    base: 10
  }
}

getDefaultValue(); // Output: { number: 50, base: 10 }

2. Single Parameter function

If Method contains single parameter then you can directly write the parameter without having (). You can also use () as well.

let getDefaultValue = number => {
  ...
  return {
    number: number,
    base: 10
  }
}

getDefaultValue(20); // Output: { number: 20, base: 10 }

3. Multiple Parameter function

If you have a method which contains multiple parameters then you can define function like below.

let getDefaultValue = (number, base) => {
  ...
  return {
    number: number,
    base: base
  }
}

getDefaultValue(40, 20); // Output: { number: 40, base: 20 }

4. Single line No Parameter function (Implicit return)

Arrow functions allow you to have an implicit return that means values are returned without having to use the return keyword. In other words, you can say single line function.

let getDefaultValue = () => ({
  number: 50,
  base: 10
})

getDefaultValue(); // Output: { number: 50, base: 10 }

5. Single line Single Parameter function (Implicit return)

Same as above, if you have single parameter then you can write the function as below.

let getDefaultValue = number => ({
  number: number,
  base: 10
})

getDefaultValue(70); // Output: { number: 70, base: 10 }

6. Single line Multiple Parameters function (Implicit return)

Let’s say if you have multiple parameters then your function should look like below.

let getDefaultValue = (number, base) => ({
  number: number,
  base: base
})

getDefaultValue(80, 35); // Output: { number: 80, base: 35 }

Here is another example for you.

let calculate = (value1, value2) => value1 + value2

calculate(5, 7); // Output: 12

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply