Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 29, 2021 06:36 am GMT

Regular vs Arrow Function

Define your functions in many ways.

One way is using function keyword:

// function declarationfunction test(msg) {    return `Hey ${msg}`}// function expressionconst test = function(msg) {    return `Hey ${msg}`}

You can call both function declaration and expression as Normal/Regular Function

Arrow function is introduced in ES6 and also known as fat arrow function.

const arrowFunction = (msg) => {    return `Hey ${msg}`}

As you see both functions work same by above example. Now the question comes why do we need regular or arrow function.

Let's discuss below

1. Syntax

2. Arguments binding

3. this

4. new keyword

5. No duplicate named parameters

6. Function Hoisting

7. Methods

1 Syntax

We can write normal and arrow function in this way

// ES5var add = function(x, y) {    return x + y};// ES6let add = (x, y) =>  x + y 

Implicit Return

In regular function, you have to use return keyword to return any value. If you don't return anything then the function will return undefined.

function regFunc() {    return "Regular Function";}regFunc(); // Regular Functionfunction regFunc() {    console.log("Regular Function")}regFunc(); // Regular Function// undefined

Arrow functions behave in the same way when returning values.

If the arrow function contains one expression, you can omit the curly braces, and then the expression will be implicitly returned.

{} not required if its only one line of statement

const addOne = (number) => number + 1;addOne(10);

() not required if you pass only one argument

let add = x => x + x;

If there is no arguments

let arrowFunc = _ => console.log("Arrow Function");

2 Arguments binding

In regular function, Arguments keywords can be used to access the arguments of which passed to function.

Example:

function regularFunction(a,b) {    console.log(arguments)}regularFunction(1,2)// Arguments[1,2]

Arrow functions do not have an arguments binding.

const arrowFunction = (a,b) => {    console.log(arguments)}arrowFunction(1,2)//ReferenceError: argumnets is not defined

However, if you want to access arguments in an arrow function, you can use the rest operator:

var arrowFunction = (...args) => {    console.log(...args)}arrowFunction(1,2)// 1 2

3 this

In regular function, this changes according to the way that function is invoked.

  • Simple Invocation:thisequals the global object or maybe undefined if you are using strict mode.
  • Method Invocation:thisequals the object that owns the method.
  • Indirect Invocation:thisequals the first argument.
  • Constructor Invocation:thisequals the newly created instance.
// 1 Simple Invocationfunction simpleInvocation() {    console.log(this);}simpleInvocation(); // Window Object// 2 Method Invocationconst methodInvocation = {  method() {      console.log(this);  }};methodInvocation.method(); // logs methodInvocation object// 3 Indirect Invocationconst context = { aVal: 'A', bVal: 'B' };function indirectInvocation() {    console.log(this);}indirectInvocation.call(context);  // logs { aVal: 'A' }indirectInvocation.apply(context); // logs { bVal: 'A' }// 4 Constructor Invocationfunction constructorInvocation() {    console.log(this);}new constructorInvocation(); // logs an instance of constructorInvocation

Arrow functions don't have their own this, and they dont redefine the value of this within the function.

this inside an arrow function always refers to this from the outer context.

var name = "Suprabha"let newObject = {    name : "supi",    arrowFunc: () => {        console.log(this.name);     },    regularFunc() {        console.log(this.name);     }   }newObject.arrowFunc(); // SuprabhanewObject.regularFunc(); // supi

4 new

Regular functions are constructible, they can be called using the new keyword.

function add (x, y) {    console.log(x + y)}let sum = new add(2,3);// 5

However, arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword

let add = (x, y) => console.log(x + y);const sum = new add(2,4); // TypeError: add is not a constructor

5 No duplicate named parameters

In normal function, we can do this:

//  will work function add(a, a) {}//  will not work 'use strict';function add(a, a) {}// Uncaught SyntaxError: Duplicate parameter name not allowed in this context

Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.

const arrowFunc = (a,a) => {}// Uncaught SyntaxError: Duplicate parameter name not allowed in this context

6 Function Hoisting

In regular function, function gets hoisting at top.

normalFunc()function normalFunc() {    return "Normal Function"}// "Normal Function"

In arrow function, function get hoisted where you define. So, if you call the function before initialisation you will get referenceError.

arrowFunc()const arrowFunc = () => {    return "Arrow Function"}// ReferenceError: Cannot access 'arrowFunc' before initialization

7 Methods

You can define methods in class using regular function.

class FullName {    constructor(name) {        this.name = name;    }    result() {        console.log(this.name)    }}let name = new FullName("Suprabha")console.log(name) // FullName{name: "Suprabha"}

You need to apply method as callback also.

setTimeout(name.result, 2000) // after 1 second logs ""

But if you bind this

setTimeout(name.result.bind(name), 2000) // Suprabha

By above example, you can see that you have to bind the this to there context.

In arrow function, you don't have to bind with context.

class FullName {    constructor(name) {        this.name = name;    }    result = () => {        console.log(this.name)    }}let name = new FullName("Suprabha")setTimeout(name.result, 2000) // Suprabha

When not to use Arrow function

Object Methods

let dog = {    count: 3,    jumps: () => {        this.count++    }}

When you call dog.jumps, the number of count does not increase. It is because this is not bound to anything, and will inherit the value of this from its parent scope.

Reference

Summary

In regular function, this value is dynamic, In arrow function it equals to this of the outer function.

In regular function, arguments will give you list of parameter passed in function, In arrow function arguments is not defined.

In regular function, you always have to return any value, but in Arrow function you can skip return keyword and write in single line.

In arrow function parameters should be unique.

Hoisting matters in arrow function as function get not be invoked before initialisations.



Thanks for reading the article

Buy Me A Coffee


Original Link: https://dev.to/suprabhasupi/regular-vs-arrow-function-4kpe

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To