Javascript – Using Arrow Functions

One of the most interesting parts of ES6 is arrow functions. Arrow functions as it sounds is the new syntax => of declaring a function. But it behaves differently from the traditional functions of Javascript.

Here is a function written in ES5 function syntax:

function absolute(num) {
	return Math.abs(num)
}	

absolute(-9) // 9
JavaScript

Now, here is the same function written using ES6 function syntax:

const absolute = num => {
		return Math.abs(num); 
}

absolute(-9) // 9
JavaScript

Arrow functions provide a concise syntax for writing function expressions.

const addNumbers = (a,b) => a + b;

console.log(addNumbers(3, 4));  // 7
JavaScript
let names = ['sujay', 'vinayak'];

// without arrow function
var abc = names.map(function (e) {
	return 'Hello " + e;
});

console.log(abc); // ["Hello sujay", "Hello vinayak"]

// with arrow function 
let xyz = names.map((e) => {
  return `Hello ${e}`;
});
console.log(xyz); // ["Hello sujay", "Hello vinayak"]
JavaScript

Implicitly return

With arrow functions we can skip the explicit return and return the value like this:

let names = ['sujay', 'sanket']

let xyz = names.map((e) => `Hello ${e}`);
console.log(xyz); // ["Hello sujay", "Hello sanket"]

const abc = e => `Hello ${e}`;
console.log(abc('sujay')); // ["Hello sujay"]
JavaScript

If there is only one parameter then we can omit the () parantheses. Also we don’t need {} braces when returning implicitly.

With implicit return, we can return object literals like below. We need to wrap the object literals inside ( ) parantheses

const quantity = "100";
const names = ["steel", "gold", "copper"];

const cost = names.map((name, i) => ({ name: quantity, price: quantity * i }));
console.log(cost);
// 0: { name: "steel", quantity: "100", price: 0}
// 1: { name: "gold", quantity: "100", price: 100}
// 2: { name: "copper", quantity: "100", price: 200}
JavaScript

Function Parameters

Function with no parameters, just add empty parantheses before =>

const abc = () => `Hello sujay`;
console.log(abc()); // Hello sujay

const pi = () => Math.PI
JavaScript

You can even replace empty parentheses with _ (underscore) :

const abc = _ => `Hello sujay`;
console.log(abc()); // Hello sujay

const pi = _ => Math.PI;
JavaScript

If you have one or more parameters, just pass them in the parentheses:

const abs = (num) => Math.abs(num) // on parameter
const sum = (a, b) => a + b // two parameters
JavaScript

For just one parameter, you can remove the parentheses :

const abs = num => Math.abs(num);  //super consise
JavaScript

Concise vs. Block body

An arrow function can have either a concise body or the block body. Depends on the statements inside.

If the function contains just one statement, use the concise body. In the concise body, only the expression is specified that implicitly returns a value (without using the return keyword):

const multiply = (a, b) => a * b //implicit return
JavaScript

In a block body, you must use an explicit return statement:

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

Look at the curly braces at the start, They are required in a block body to wrap statements:

const oddNumber = num => {
	if (num % 2 === 0) {
		return false;
	} else {
		return true;
	}
}
JavaScript

Object Literals

If you are returning an object literal using the concise body, it must be wrapped in parantheses to avoid it being treated as a block body:

const json = () => ({ x: 2 })
JavaScript

Using with REST Parameters

We can use Rest parameters (…variable) as well in the fat arrow function in Javascript

const quantity = "100";
const names = ["steel", "gold", "copper"];

const cost = (quantity, ...names) => {
	console.log(quantity);
	console.log(names);
};

cost(quantity, names, names);
// 100
// (2) [Array(2), Array(3)]
// 0: ["steel", "gold", "copper"]
// 1: ["steel", "gold", "copper"]
JavaScript

With Default Parameters

We can define default parameters :

const quantity = 100;

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

cost(quantity); // 100 (not passing value for price)

cost(quantity, 20); // 2000 (passing value for price)
JavaScript

When not to use the Arrow function !

this keyword

In regular function expressions, the this keyword is bound to a different value based on the context in which that function is called:

  • A new object in case of constructor
  • undefined in strict mode function calls.
  • The parent object of the function is called an object method.

For example, Here is a person object which has the fullName() function:

const person = {
	firstName: 'John',
	lastName: 'Doe'.
	fullName: funtion () {
		return `${this.firstName} ${this.lastName}`
	}
}

person.fullName() // John Doe
JavaScript

However, an arrow function does not have the this keyword and is lexically bound. It essentially means that the this scope is inherited from the code that contains the arrow function.

While looking up for this that is not present in the current socpe, the ES6 arrow function will use the value of this in the scope in which it was defined. That is why the call to fullName() will not work and will return an undefined value.

const person = {
	firstName: 'John',
	lastName: 'Doe',
	fullName: () => {
		return `${this.firstName} ${this.lastName}`
	}
}

person.fullName() // undefined undefined 
JavaScript

Because of this, arrow functions are not suited to object methods. You should also not use them as constructors either to avoid errors.

DOM Event Handling

Arrow functions can be a problem, while handling events. DOM event listeners set this to be the target element. Now, if you use the arrow function for callbacks, the this keyword won’t be bound to the target element but to its parent scope.

const button = document.getElementsByTagName('button');
button.addEventListener('click', () => {
	this.classList.toggle('blur')
});
JavaScript

If you click the button, you will get a TypeError because this refers to the window object in this scope. If you need a dynamic context for the callback function, a regular function expression is required:

const button = document.getElementsByTagName('button')
button.addEventListener('click', function () {
	this.classList.toggle('blur');
});
JavaScript

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *