Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arrow
javascript
function

Arrow function vs. traditional function in JavaScript

Educative Answers Team

Introduction

Arrow function or an arrow function expression is a more concise syntax of writing regular function expressions that allows us to write shorter and neater functions. Arrow functions were introduced in ECMAScript 6 (2017). They are also known as a fat arrow function as they utilize the => token, which is shaped like a fat arrow.

Syntax

Their concise syntax allows us to at times avoid writing return tokens, function token and curly brackets. Let’s take a look at the following syntax.

var func = (<Arguments>) => {
    //instructions
    return <Value>;
}

The above syntax shows how we generally write an arrow function. The curly brackets encapsulate the set of instructions that we can write as we do in a general function. Meanwhile, the fat arrow => is the token used to represent the arrow function which is preceded by parentheses containing the arguments of the function.

var func = (<Arguments>) => <Expression/Value>;

Moreover, we can make the representation of an arrow function more concise if we had a one-line function. For a one-line function, we can drop the curly brackets and the return statement as the expression or value is implicitly returned after the => token.

Comparison

Take a look at the following comparison between the two styles of writing functions.

Arrow function

var func = (a, b) => { 
    var sum = a + b;
    return sum;
}

Uses => in function definition.

Traditional function

function func (a, b) { 
    var sum = a + b;
    return sum;
}

Uses function keyword in function definition.

Examples

Let’s see some examples to see the arrow functions in action.

var func = (a, b) => { 
    var sum = a + b; 
    return sum; 
}
console.log("Sum of 1 and 3:" , func(1,3)); 

In the code above, we create an arrow function to take the sum of two variables passed as argument which, in our case, is a and b.

We can convert this into a single line of code too using arrow functions.

var func = (a, b) => a + b; 
console.log("Sum of 1 and 3:" , func(1,3)); 

Since we need to return a + b for the sum, we can directly write the function in one line where the arrow function takes two variables a and b as arguments and then return the expression a + b. Do note how our code is now more concise thanks to arrow functions.

NOTE: Arrow functions can also be called anonymous functions as they are unnamed functions.

RELATED TAGS

arrow
javascript
function
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring