Arrow Functions – JavaScript

Let’s take an example of a normal function:

We’re writing a function that takes 2 values – a & b and then returns the sum of them both.

function sum(a, b) {
  return a + b
}

console.log(sum(1, 2))

Now, let’s convert it to an Arrow function. After that, I’ll explain everything we did.

let sumArrow = (a, b) => {
  return a + b
}

console.log(sumArrow(1, 2))

Changes we did:

  • Remove the word function
  • Create a variable and assign it
  • Added an arrow => between parenthesis and curly brackets

Now, we can call the function by the variable and then put in the parameters.

You can eliminate the parentheses if you only have 1 argument. Here’s an example:

let printName = name => {
  console.log(name)
}

This will only apply when you have 1 argument.

If you only have one line in your function, you can also remove the curly brackets. Here’s an example:

let printName = name => console.log(name)

These ‘tricks’ are completely optional though.

How to create an Arrow Function with no parameter?

let exampleArrow = () => {
 console.log('easy')
}

We just leave the space empty. Easy.

Why do you use an Arrow Function?

Its main use is passing functions in OTHER functions. It’s shorter and easier.

You can build Anonymous Functions too. You can’t do this with a normal function.

() => {
 console.log('condition')
}

You don’t need to write the word ‘function’ or even a variable when you create an anonymous arrow function.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts