Arrow Function: Basics

bhagatparwinder

Parwinder 👨🏻‍💻

Posted on July 20, 2020

Arrow Function: Basics

Introduction

Arrow functions introduced in ES6 is a concise way of creating functions compared to function expressions.

The name arrow function comes from the use of =>.

Syntax:

const functionName = (arg1, arg2, ... argN) => {
    return value;
}

Example

const multiply = (a, b) => {
    return a * b;
}

console.log(multiply(7, 8)); // 56
console.log(multiply(3, 2)); // 6

Key Features

  • Arrow functions are anonymous function until they are assigned to a variable.
  • If there is only 1 argument, we can skip parenthesis.
   const square = x => {
       return x * x;
   }

   console.log(square(2)); // 4
   console.log(square(7)); // 49

The only caveat to this rule is that if the 1 argument is destructured.

const foo = ({name = "New User"}) => name;

console.log(foo({})); // New User
console.log(foo({name: "Parwinder"})); // Parwinder
  • If there are no arguments, we need to have the parenthesis
   const greeting = () => {
       return "Hello World!";
   }

   console.log(greeting()); // Hello World!
  • If the function body is an expression, it will return the expression, we can remove the brackets and the return keyword.
   const greeting = () => "Hello World!";
   console.log(greeting()); // Hello World

Now that we know all these key features, let us rewrite the example to get the square of a number:

const square = x => x * x;
console.log(square(4)); // 16
💖 💪 🙅 🚩
bhagatparwinder
Parwinder 👨🏻‍💻

Posted on July 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning For Loop In Javascript
javascript Learning For Loop In Javascript

May 16, 2023

Memoization in JavaScript
javascript Memoization in JavaScript

October 10, 2020

Polymorphism in JavaScript
javascript Polymorphism in JavaScript

October 11, 2020

Currying
javascript Currying

October 4, 2020