DEV Community

Cover image for Arrow Functions in JavaScript: A Simpler Way to Write Functions
Anoop Rajoriya
Anoop Rajoriya

Posted on

Arrow Functions in JavaScript: A Simpler Way to Write Functions

In this article we will discuss about different way of declaring function, how you use and declare them? and the major difference between them. By the end of the article you will understand more about the Regular and Arrow function in JavaScript.


What arrow functions are

Arrow function is the consice way of writing function in javascript. It give ability so you can skip the boilerplate code which you write every time in function declaration before ES6.

Arrow function support more features like lexical this binding, implicit return, more predictability than normal function.

Every normal function declaration required boilderplate setup code like function keyword, {} curly braces, and return keyword.

function greet (name){
    return `Hello! Good Morning ${name}`
}
Enter fullscreen mode Exit fullscreen mode

But with arrow function it become optional it can be skipped. It only needed in some cases.

const greet = name =>`Hello! Good Morning ${name}`
Enter fullscreen mode Exit fullscreen mode

Basic arrow function syntax

Any basic arrow function requried three things for declaration parameters for accepting arguments, fat arrow symbol =>, and function body.

It always created as anonymously (not contain any name) and assigned to a variable to create reference so can be used later.

Normal Function Syntax:

/* Basic setup required
function name (parameters){
    body
    return value
}
*/

function square (n){
    return n**2
}
Enter fullscreen mode Exit fullscreen mode

Arrow Function Syntax:

const squre = n => n**2
Enter fullscreen mode Exit fullscreen mode

Arrow functions with one parameter

As we shown above examples if your arrow function only have one parameter than you can skip () parentheses and direct write name of the parameter.

const squre = n => n**2
Enter fullscreen mode Exit fullscreen mode

Arrow functions with multiple parameters

In case of multiple parameters you need to wrape you arguments in () parentheses else first parameters are skipped.

/* Wrong syntax: a will skipped
const sum = a,b => a+b
*/

const sum = (a,b) => a+b
Enter fullscreen mode Exit fullscreen mode

Implicit return vs explicit return

Returning value form normal function declaration required to use of return keyword, but in case of arrow function you can skip it.

Implicit Return

When you funciton body can fit in one line or it can be a expression than you can skip {} curly braces and return keyword in arrow function.

// a+b --> expression
const sum = (a,b)=>a+b
Enter fullscreen mode Exit fullscreen mode

In case of returning object literals you need to wrap it by () parentheses to aboud JS interpeting object braces as function body.

const user = ()=>({name:"user", age:30})
Enter fullscreen mode Exit fullscreen mode

Explicit Return

If you function contain more than one line of code than you need to wrap it in {} curly bracess and use return statement for returning value.

const checkOdd = (n)=>{
    if(n%2 === 0) return "Odd"
    else return "Even"
}
Enter fullscreen mode Exit fullscreen mode

Basic difference between arrow function and normal function

Both are used used to abstract code block and perform task in same way but still both have some key difference:

1. Concise way to write code

We discuss it already discuss about that, normal function use function keyword and the arrow function use shorthand way to reduce this boiler plate code.

// normal function
function greet (name){return `Hello, ${name}`}

// Concise way to write it
const greet = name=>`Hello, ${name}`
Enter fullscreen mode Exit fullscreen mode

2. this keyword behaviour

In normal function this is dynamically bound to the function (means it have its own this object) but in arrow function it inherit this from its lexical scope (code surrounding it).

// Timeout with normal function print undefined becuase its detached during execution and have its own this, which not have name

// But Arrow function print "Arrow Timeout" because it inherit code surrounded them (lexical inheriting)

const obj3 = {
    name: "Arrow Timeout",
    sayName: function () {
        setTimeout(function () {
            console.log("function(){}", this.name)
        }, 1000)
        setTimeout(() => {
            console.log("()=>{}", this.name)
        }, 1000)
    }
}

obj3.sayName()
// function(){}: undefined
// ()=>{}: Arrow Timeout
Enter fullscreen mode Exit fullscreen mode

3. arguments object

Regular function have arguments object which os a iterable list object which holds all the arguments passed to it and you can access it within.

But in arrow function you don't have access arguments object because it not have that But we can use rest paramets to acheiving it.

function showArgs() {
    console.log(arguments);
}
showArgs('a', 'b', 'c'); // Output: { '0': 'a', '1': 'b', '2': 'c' }

const showArgsArrow = () => {
    // ReferenceError: arguments is not defined
    console.log(arguments);
};
showArgsArrow('a', 'b', 'c');
Enter fullscreen mode Exit fullscreen mode

Both have those tradoffs some times you need regular function and some types you will need arrow function. Understanding both and the differece: syntax, this binding, arguments object and usecase will makes you to predict code flow required in today world of development.

Top comments (0)