Quick links
Latest articles
Internship
Members
New...
Algorithms
Discrete Mathematics
Big data
Languages
C
C++
C++ STL
Java
Data Structure
C#.Net
Android
Kotlin
SQL
Web
PHP
Python
JavaScript
CSS
Ajax
Node.js
Web prog.
Programs
C
C++
DS
Java
C#
Python
Aptitude
C
C++
Java
DBMS
Interview
C
Embedded C
Java
SEO
HR
CS Subjects
CS Basics
O.S.
Networks
DBMS
Embedded Systems
Cloud Computing
Machine learning
CS Organizations
Linux
DOS
More...
Articles
Puzzles
News/Updates

Home » JavaScript Tutorial

Arrow function in JavaScript



In this tutorial, we will learn what is an Arrow function and conversion of functions to arrow function?
Submitted by Himanshu Bhatt, on September 07, 2018

Arrow Function are short, makes a lot of sense, they are new and modern, it’s amazing and is short syntax and tactic-sugar. Arrow functions were introduced in JS ES6 (ES 2015).

Let’s start with a code with a traditional function to have a comparison with arrow function.

Code snippet 1

const sayHello = function (name){
	return "Hey there, " + name +"!"
}
console.log (sayHello ('Sam'));

Now it’s pretty much clear what’s going in the above code snippet and the output is "Hey there, Sam!"

We use now arrow function to change above code.

Code snippet 2

const sayHello = (name) => "Hey there, " + name +" !"
console.log(sayHello('Sam'));

Output for both the code will be the same. Let's analyze the arrow function, as we can see that in the Code snippet 2 we do not use function keyword instead used '=>' (arrow symbol) also, we do not have any return statement but directly passed the same statement in Code snippet 2 which we passed under the return of Code snippet 1.

Syntax:

 
    (param1, param2, param3, ...) => {statement}

Where, {statement} is equivalent to => { return expression}

Note: if statement is one line long we can omit the curly braces but the sake of clean code we prefer them and same with parenthesis if there is a single parameter then we can omit them too.

Now let’s deal with functions with objects:

Example [Code snippet 3]:

const names =[{
	name: 'Sam',
	value: 0,
},{
	name: 'Tom',
	value: 1,
},{
	name: 'Max',
	value: 0,
}]

const valueZero = names.filter((name) =>name.value === 0)	//line 1

// constvalueZero = names.filter(function(name){			//line 2
//     return name.value === 0 
// })

console.log(valueZero);

Explanation:

In code snippet 3, we have an array of objects names which contains 3 names Sam, Tom, and Max with values 0, 1, 0 respectively. As we can compare the line 1 and line 2 (which are commented out) serves the same purpose but line 1 with arrow function is more concise and cleaner than the normal function in line 2 which are lengthy.

In line 1 (or line 2), we used a method filter() which returns elements (in our case whole object) of the array which meet a certain condition, also it requires a callback function. So in our line one, we used arrow function as our callback function.

Output:

[ { name: 'Sam', value: 0 }, { name: 'Max', value: 0 } ]

Tips – Do's and Don'ts:

1. Caution with THIS keyword and Arrow Function

Well, so far we have seen arrow functions are so cool, easy to use and concise. So should we use arrow functions everywhere? The answer is pretty much ‘no’. What I mean let me demonstrate it with this keyword in following example [Code snippet 4]:

Example [Code snippet 4]

let javascript = {
	totalArticles: 105,
	totalContentWriter: 3,
	description1:() => {
		return `IncludeHelp have ${this.totalArticles} articles on JavaScript provided by 
		${this.totalContentWriter} content writers`
	},
	description2: function() {
		return `IncludeHelp have ${this.totalArticles} articles on JavaScript provided by 
		${this.totalContentWriter} content writers`
	}
}
console.log(`Description2: ${javascript.description2()}`);
console.log(`Description1: ${javascript.description1()}`);


Output

Arrow function JS code output 1

Explanation:

Now we created an object named javascript which contain about the total number of articles and content writer contributed for it on IncludeHelp.com (It is a hypothetical data, not real). So we created two functions, out of one is an arrow function. Now we make both description1 and description2 similar but in the output, arrow function returned undefined while the required output was returned with normal function. This is because of this keyword<, it is a nightmare for a lot of people and generally a beginners’ mistake, it (this keyword) automatically binds for you in JS, sometimes it binds with windows objects, sometimes it binds with function objects and there was no way to control it, now in arrow function nothing is bind neither the arguments nor this so they are completely free, thus we need to explicitly bind it if we really want to use it in this manner.

2. Never use arrow Functions with methods or constructors

There can be use case scenario but most of the times people like to avoid them.

3. In Redux

There is one thing we do in Redux is returning back a lot of key-value pairs and using the arrow function we can use it, but here is a word of caution.

Example:

    const func = () => {key: 'value'}    
    //output : undefined

If you do something like that you’ll be getting undefined. So right way is:

    const func = () => ({key: 'value'})		
    //output : {key: 'value'}





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Featured post:
Introduction to Linux (Its modes, Safety, Most popular Applications)
Linux Best Distribution Software (Distros) of 2018

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.