logo

NJP

Arrow Functions - Let's Learn ECMAScript 2021 with Earl Duque

Import · Jan 25, 2024 · video

Arrow functions. That's right. We finally have access to arrow functions. So let me show you the traditional way
that we would normally do functions. So let's say we are creating
this function called add. And we have two variables
that we want to pass into it. And the return is something
as simple as a plus B. All right. So that's the normal way
we would have wrote that function. And the new way to do it
via arrow function would look like this. So let's say
addArrow is our function name. And what that looks like is
we would say first, what are our variables
that we're passing into it. And we would make a little arrow
with an equal and greater than caret. And then say what we want to happen
with those variables inside of it. And there you go. That's the that's the new way
to write that function in one single line. So let's go ahead and test it. We'll do both, actually. So add three and four. Then gs.info addArrow three and four. There you go, same thing. So before we move on,
why are we using arrow functions? Besides, for the reasons
of their very concise looking and they are copy and paste-able
from StackOverflow forums. They're particularly helpful in situations
where you're trying to preserve the context of this
within callbacks or other methods. So what does that look like? Let me show you. So let's say we have a object called user, So inside of that object,
we have a name of Fred. And we have a function inside of there, which is actually an arrow function. And inside of that, it's a log statement that says this.name and close that. So let's try to call that. So instead of using a log statement because there's already one
existing in there, we're going to go ahead and use that one. We're going to say user.logName
and call it. If I run this, it's undefined. And that's a good thing
because when I used a arrow function, It means that the this is being preserved within the context
that it's being called in. The statement here has no context of this. So it has nothing to return. But let's say I have a function
called other context, And in this function,
my this context as a name is actually Abel. And if I call log name from within this context
and let's call that function. Let me get rid of this line right here and run it. It says Abel. It maintained the context of this in its separate callback. That's very useful,
especially with usual function declarations the
this gets all funky all over the place. if you've ever built a script include
inside ServiceNow, you know how confusing this gets all over the place. So having a little bit more control of when this gets manipulated
or not is useful. Arrow functions.

View original source

https://www.youtube.com/watch?v=zkPim4w9yMs