Understanding Functions and Arrow Functions in JavaScript


Output will be Hello Alicegreet
is a regular function, so when user.greet()
is called, this
inside greet
refers to the user
object.
Inside
greet
, it returns an arrow function.Arrow functions do not have their own
this
. They lexically inheritthis
from their surrounding scope — in this case, thegreet
function.Since
greet
was called onuser
,this
ingreet
points touser
, and so the arrow function also "remembers" thatthis
.
In this match output will be undefined and 25
Since sayAgeArrow: Is a arrow function so it don’t have own this and it inherit from lexical env so in this case it refer to window obj in case of browser and in case of node it refer to global object that is undefined So that is the reason it’s print undefined
sayAgeRegular: Is a regular function so it have it own this and here this will point to person object so it will return 25 (this.age)
Higher Order Function
Output => 8,2
Subscribe to my newsletter
Read articles from Nishit Ranjan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nishit Ranjan
Nishit Ranjan
Self-taught frontend developer on a mission to master JavaScript and web development. Sharing my journey, tips, and hard-learned lessons through blogs and projects.