Arrow function in javascript example





Hey guys in this post we will learn about the javascript arrow function and some of the examples.

What is an arrow function?


Javascript arrow function or arrow function expression is a shorter alternative to the regular javascript function definition syntax.

Syntax


The arrow function expression supports multiple different syntaxes and we will see a few of them

/* function has multiple parameters */ 
(param1, param2, ..., param3) => {statements}

/* function has single parameter */ 
(param1) => {statements}

/* function has no parameters */ 
() => {statements}

In the case of a single parameter, using parenthesis () is optional, we can also define the arrow function expression like this

param => { statements }

And if we have a single expression to return some output, we can even skip the curly braces {} like this

param => { return expression; }
/* we can written as */
param => expression;

Examples


Normal function

let add = function(a, b) {
  return a+b;
}

let sum = add(2, 5);
console.log(sum);

Arrow function

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

let sum = add(2, 5);
console.log(sum);

Things you should avoid with arrow function


1. You should not use arrow functions to create methods inside objects

let person = {
  name: 'Jhon',
  age: 30,
  sayHello: () => {
    // `this` refers to the global
    console.log(`${this.name} is ${this.age}`);
  }
}

person.sayHello(); //undefined is undefined

2. You cannot use an arrow function as a constructor.

let Foo = () => {};
let foo = new Foo(); //TypeError: Foo is not a constuctor




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply