DEV Community

Understanding Callbacks

Briggs Elsperger on March 15, 2022

Understanding Callbacks Callbacks seem to be a sticking point for people new to programming. Put simply, callbacks are functions that ar...
Collapse
 
peerreynders profile image
peerreynders • Edited

These are just a shorter way to write a function.

I understand this is content for beginners ... but there seems to be this idea that arrow functions were introduced in ES2015 for their fashionable terseness.

The reason for their inclusion is that they are different to traditional function expressions - which is related to their use as callbacks.

MDN: "Arrow functions establish this based on the scope the Arrow function is defined within."

See also: Function Context.

In practical terms this means that when an arrow function is created inside an object method it automatically binds to the this of the object the method was called on, so it retains access to the original creating object even when it's passed as a callback to another function (or method of another object).

Regular functions do not behave this way. Regular functions have to be explicitly bound to the object.

As a trade off arrow functions don't support apply, bind, or call and as a consequence arrow functions cannot be shared via the prototypal inheritance mechanism (given that each arrow function's this is statically bound it no longer can be shared via a dynamically passed this).

function log(text) {
  console.log(`${text}: ${this.someValue}`);
}

const instance = {
  someValue: 'Instance',
  passArrow() {
    const callback = (text) => log.call(this, text);

    setTimeout(callback, 100, 'Arrow');
  },
  passFn() {
    const callback = function (text) {
      log.call(this, text);
    };
    setTimeout(callback, 200, 'Function');
  },
};

globalThis.someValue = 'Global';
instance.passArrow(); // Arrow: Instance
instance.passFn(); // Function: Global
Enter fullscreen mode Exit fullscreen mode
Collapse
 
i3uckwheat profile image
Briggs Elsperger

That's exactly why I added We're going to ignore the this binding rules for these functions for now. in the article, perhaps I should have expanded on that a bit more. This comment here explains it very well though!

Collapse
 
peerreynders profile image
peerreynders

Re-reading that paragraph again:

"Arrow functions differ from regular functions in some nuanced ways. To simplify the discussion we're steering clear of those differences."

Beginners tend to latch onto "just a shorter way to write a function" as "the truth" because it's so (convenient and) easy to remember - using it as a justification to use arrow functions exclusively even when it's inappropriate (e.g. as class methods).

Thread Thread
 
i3uckwheat profile image
Briggs Elsperger

I'll consider making some edits, thank you

Collapse
 
alexerdei73 profile image
AlexErdei73

Thank Mr Elsperger for the great article. The article is really illuminating regarding callbacks. He is well aware that there is a minor difference regarding the context between arrow functions and regular functions. It is perhaps more important than the syntax difference as anybody with a little ES6 JS experience can refactor one form to the other. This comment is great to point out the real difference between the two with this great code sample. Maybe the code sample can be simplified slightly to make it more obvious, what's going on.
The important question is weather the article should contain this difference as detailed as in this comment. In my opinion Mr Elsperger is not far from the truth that real beginners can get confused with details like this. I think he has got experience with these people as he contributes actively to The Odin Project, which is a curriculum for people, who want to become self trained web developers, like myself.
As far as I have seen this is the only real difference between arrow functions and regular function expressions, therefore it would be great to include it in the article in some less confusing form. He could use for example small print and warn beginners that they can skip this part not to get confused. This is common practice in scientific articles.
Why is this fine detail less important? JS is not a language for primarily doing OOP, but functional programming. It means listeners hardly ever use 'this'. It's a concept of OOP, where inheritance is highlighted. Of course people, who want use JS for OOP or people who use React class components (OOP syntax) must be aware of all this.

Collapse
 
peerreynders profile image
peerreynders

JS is not a language for primarily doing OOP, but functional programming.

  1. JavaScript is not a "functional programming language"
  2. In JavaScript class is merely a template for creating objects; it's not a class in the class-based object oriented sense.
  3. this is called the function context; so it can be used to access the object the function was invoked on but it is also used in other ways.

Please read this: Function-Oriented

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Very nicely explained 😀

Collapse
 
konadulord profile image
Konadulord

Head aching but I will grab it

Collapse
 
marcomoscatelli profile image
Marco Moscatelli

Great content for beginners!

Collapse
 
gotw profile image
GorkhaOnTheWeb

The comment section made me feel so dumb.

Collapse
 
nandkishorjadoun profile image
Nandkishor Jadoun

you mean @peerreynders ?

Collapse
 
rootadbc profile image
rootadbc

from ODIN

Collapse
 
rakshitambi7a profile image
Rakshit Ambi

Thanks for this article. It's the first time I've read about callbacks without feeling confused or overwhelmed."

Collapse
 
khaledyd profile image
khaledyd

it's what i needed the most to understand the callbacks and fucntion , becouse of this post i can understand what's funtion and whats not this is amazing , thank you so much

Collapse
 
brunoj profile image
Bruno

love this