Javascript: Regular Functions vs Arrow functions?

Javascript: Regular Functions vs Arrow functions?

Motivation

wanted to understand how it actually works

Syntax

Regular functions

function test() {
    console.log("test");
}

var test= function () {
    console.log("testing normal functions");
}

Arrow Functions


let test= (x+y) => { console.log("testing")}

Difference

  1. Arguments binding works in Normal functions and does not work in arrow functions.

image.png

main difference

this keyword usage

this keyword usage changes in regular and arrow functions , since when we use the regular functions, and invoke a method inside a class it will be scoped based on from where we are calling it , but in case of arrow functions it will be scoped within the class

class Student {

  constructor(name) {
   this.name=name;
  }

  printRegularFunctions() {
    setTimeout(function() {
     console.log("inside normal function" +  this.name)
    } ,100);
  }


  printArrowFunctions() {
    setTimeout(()=> {
     console.log("inside arrow function  "+this.name)
    } ,100);
  }
}

let s1=new Student("sandy");
s1.printRegularFunctions();
s1.printArrowFunctions();

output

Arrow function will print the output : sandy Regular function will not print anything here.