Arrow functions in JavaScript

Bobby SadhwaniBobby Sadhwani
4 min read

Arrow functions were introduced in ES6. It behaves differently from the traditional functions of Javascript.

Syntax

const functionName = (parameters) => {
    //function body
}
const getName = (age) => {
    let name = 'Bobby';
    return `${name} is ${age}`;
}

let name = getName(23);
console.log(name); // Bobby is 23

Shorthand Syntax

If the arrow function has only one statement, you can skip the curly braces and the return keyword.

const getName = (age) => `Bobby is ${age}`;

let name = getName(23);
console.log(name); // Bobby is 23

If the arrow function has only one parameter, you can skip the parentheses as well.

const getName = age => {
    let name = 'Bobby';
    return `${name} is ${age}`;
}

let name = getName(23);
console.log(name); // Bobby is 23

If the arrow function has only one statement and if it is returning an object literal, use parentheses to wrap that object literal otherwise it will not work as expected.

const fun = () => {name : 'Bobby'} // undefined

const fun = () => ({name : 'Bobby'}) // { name: 'Bobby' }

Rest Parameters

We can use the rest parameter inside an arrow function.

const quantity = "100";
const names = [ "Iron", "Gold", "Aluminium" ];

const estimate = (quantity, ...names) => {
   console.log(quantity); //100
   console.log(names); //(6) ['Iron', 'Gold', 'Aluminium', 'Iron', 'Gold', 'Aluminium']
}; 
estimate(quantity, ...names, ...names);

Default Parameters

We can define default Parameters inside the arrow function.

const quantity = 100;

const estimate = (quantity, price = 1) => {
   console.log(quantity * price);
}; 
estimate(quantity); //100

estimate(quantity, 20); //2000

Destructuring

Destructuring with parameters is also supported inside the arrow function.

let myFun = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
myFun(); // 6

No this of its own

Value of this keyword is determined by the containing function in which the arrow function is defined. this keyword inside an arrow function refers to the this of containing or parent function.

// Adding a default property to the global object, which is window in browers. 
window.default = 100

var increment = {
  default: 1,
  start: function(){
     setTimeout(function(){
        console.log(this.default + 1);
     }, 1000);
   }
}

increment.start() // 101

In the above, we have a traditional function an object method, and the traditional function inside an object method refers to the global object i.e., the window object in browsers. That is why it is increasing the default value of the window object rather than the increment object.

// Adding a default property to the global object, which is window in browers. 
window.default = 100

var increment = {
  default: 1,
  start: function(){
     setTimeout(() => {
        console.log(this.default + 1);
     }, 1000);
   }
}

increment.start() // 2

In the above, we have an arrow function and an object method, and the arrow function refers to the this of containing function i.e., the increment object in the above code. That is why it is increasing the default value of the increment object rather than the window object.

this using call(), apply(), or bind()

We cannot change the value of this using call(), apply(), or bind inside an arrow function.

var increment = {
  base: 1,
  add: function(a) {
    let f = v => v + this.base;
    return f(a);
  },
  addAgain: function(a){
    let f = v => v + this.base;
    return f.call({base: 10}, a);
  }
}

console.log(increment.add(10)); //11
console.log(increment.addAgain(12)); //13
// {base:10} is ignored.

No constructors

We cannot use arrow functions with new keyword as constructor, Doing so will result in an error.

 const abc = () => `Hello Prashant`;
 let x = new abc();
 //abc is not a constructor

No arguments binding

Arrow functions don’t have arguments object.

// Argument object inside Tradional Function
function myFun(a, b, c){
    console.log(arguments) // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    console.log(arguments[2]) // 3
}
myFun(1, 2, 3)

// Argument object inside Arrow Function
const myFun2 = (a, b, c) => {
    console.log(arguments)
}
myFun2(1, 2, 3) // Uncaught ReferenceError: arguments is not defined

No prototype property

The prototype property does not exist for the arrow function in javascript.

 let args = ['Bobby', 'Sadhwani'];
 // Arrow Function
 const myFun = (...args) => args[0];
 console.log(myFun.prototype); //undefined

 // Tradional Function
 function myFun2(...args){
     args[0]
 };
 console.log(myFun2.prototype); 
 /*
 {constructor: ƒ}
 constructor : ƒ myFun2(...args)
 [[Prototype]] : Object
 */

Unique parameters

Unlike traditional Javascript functions where we can use duplicate parameters in unstrict mode. In arrow functions we cannot use duplicate parameters at all.

 function myFun(a, a, a){
  console.log(a);
 }
 myFun(12, 10, 23); //23

 const myFun2 = (a, a, a) => {
   console.log(a);
 }
 myFun2(12, 10, 23); //SyntaxError: Duplicate parameter name not allowed in this context

No yield keyword

We cannot use arrow functions as a generator function. Because the yield keyword may not be used inside the arrow function.Except when permitted within functions further nested with it.

Final Words

And that’s it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next blog.✌️

0
Subscribe to my newsletter

Read articles from Bobby Sadhwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bobby Sadhwani
Bobby Sadhwani

I'm a front-end developer focused on crafting clean and user friendly experiences.