Usefulness of callback functions

后端 未结 5 887
鱼传尺愫
鱼传尺愫 2021-01-18 11:04

In Javascript there is a possibility to define a function X and pass it as an argument to another function Y.

Such a function X is called a callback function

5条回答
  •  礼貌的吻别
    2021-01-18 11:20

    Callbacks are inevitable if you do any kind of event listening. JavaScript and event-driven paradigm are brothers in arms. User interaction as presented in web browsers is the reason.

    Whether you listen to DOM events, Ajax completion, file system access or HTTP requests in Node.js, you must define a procedure to be called upon event occurring.

    More advanced form of callbacks are promises, for instance.


    Also, callbacks are handy as iteration processors:

    [ 1, 2, 3 ].forEach(function callback(val) { console.log(val); });
    

    The following could replace all letters with their code-points:

    'hey hop hello'.replace(/./, function callback(s) { return s.charCodeAt(0); });
    

提交回复
热议问题